<div class="container">
<div class="form-inline my-2">
<div class="form-group mr-2">
<input type="text" class="form-control" id="name" placeholder="請輸入姓名">
</div>
<div class="form-group mr-2">
<input type="email" class="form-control" id="email" placeholder="請輸入 email">
</div>
<button type="button" class="btn btn-primary mr-2" id="add">新增</button>
<button type="button" class="btn btn-danger" id="clear">清除全部</button>
</div>
<ul></ul>
</div>
let users = [];
if (localStorage.getItem("users")) {
users = JSON.parse(localStorage.getItem("users"));
showData();
}
$("#add").click(function(){
let name=$("#name").val(), email=$("#email").val();
let newUser={
name: name,
email: email
}
users.push(newUser);
localStorage.setItem("users", JSON.stringify(users));
$("ul").append(`<li>${name}: ${email}<button class='btn btn-primary btn-sm'>x</button></li>`);
})
function showData(){
users.forEach(function(user, index, array){
$("ul").append(`<li class="my-1">${user.name}: ${user.email} <button class='btn btn-primary btn-sm'>x</button></li>`);
})
}
$("ul li").on("click", ".btn", function(){
let index=$(this).parent().index();
users.splice(index, 1)
$(this).closest("li").remove();
localStorage.setItem("users", JSON.stringify(users));
console.log(users)
})
$("#clear").click(function(){
localStorage.clear()
$("ul").empty()
})