動態表單通訊錄
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<style>
</style>
</head>
<body>
<div class='app'>
<div>
<button class='add-btn'>新增聯絡人</button>
</div>
<div class='contacts'>
<div class='row'>
姓名:<input name='name'>
電話:<input name='phone'>
<button class='delete'>刪除</button>
</div>
</div>
</div>
<script>
document.querySelector('.add-btn').addEventListener('click', function() {
const div = document.createElement('div')
div.classList.add('row')
div.innerHTML = `
姓名:<input name='name'>
電話:<input name='phone'>
<button class='delete'>刪除</button>`
document.querySelector('.contacts').appendChild(div)
})
document.querySelector('.contacts').addEventListener('click', function(e) {
if (e.target.classList.contains('delete'))
document.querySelector('.contacts').removeChild(e.target.closest('.row'))
})
</script>
</body>
</html>
簡易密碼產生器
程式碼還可以優化。各有優缺點。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<style>
body {
font-size: 24px;
}
.result {
background: rgba(0,0,0,0.2);
}
</style>
</head>
<body>
<div class='app'>
<div><label><input type='checkbox' name='en'/>英文</label></div>
<div><label><input type='checkbox' name='num'/>數字</label></div>
<div><label><input type='checkbox' name='sp'/>特殊符號</label></div>
<div>
<button class='btn-generate'>產生</button>
</div>
<div class='result'>
ssssasdasdqwe
</div>
</div>
<script>
document.querySelector('.btn-generate').addEventListener('click',
function () {
let availableChar = ''
if (document.querySelector('input[name=en]').checked) {
availableChar += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
}
if (document.querySelector('input[name=num]').checked) {
availableChar += '0123456789'
}
if (document.querySelector('input[name=sp]').checked) {
availableChar += '!@#%&*$?()'
}
let result = ''
for (let i = 0; i < 10; i++) {
// Math.random() 產生 0 ~ 0.9999999
const number = Math.floor(Math.random() * availableChar.length)
result += availableChar[number]
}
document.querySelector('.result').innerText = result
}
)
</script>
</body>
</html>