添加新联系人似乎获得了我输入的值。但不知何故,我只看到它一秒钟,并没有停留在我附加到它的html表。我知道这里的一些功能还没有完全发挥作用,但现在对我来说重要的是这个添加联系按钮至少有效。
var addressBook = (function() {
var contact = [{
firstName: 'myName',
lastName: 'lastName',
number: '123456789',
email: 'myEmail@gmail.com'
}];
var table = $('#table');
var tbody = table.find('tbody');
var form = $('#createForm');
var $firstName = form.find('#firstName');
var $lastName = form.find('#lastName');
var $number = form.find('#number');
var $email = form.find('#email');
var $addButton = form.find('#addButton');
var $deleteButton = table.find('#deleteButton');
var $input = table.find(".edit");
$addButton.on('click', addContact);
table.on('click', '#deleteButton', deleteContact);
addedContact();
function addedContact() {
tbody.html('');
var length = contact.length;
for (var i = 0; i < length; i++) {
table.append('<tr><td><input class="edit" type="text" value="' + contact[i].firstName + '"></td><td><input class="edit" type="text" value="' + contact[i].lastName + '"></td><td><input class="edit" type="text" value="' + contact[i].number + '"</td><td><input class="edit" type="text" value="' + contact[i].email + '""></td><td><button id="deleteButton value = "DELETE"></button></td></tr>');
}
}
function addContact() {
var newPerson = {
firstName: $firstName.val(),
lastName: $lastName.val(),
number: $number.val(),
email: $email.val()
};
contact.push(newPerson);
$firstName.val('');
$lastName.val('');
$number.val('');
$email.val('');
addedContact()
}
function deleteContact(event) {
var element = event.target.closest('tr');
var i = table.find('td').index(element);
contact.splice(1, 1);
addedContact();
}
return {
addContact: addContact,
deleteContact: deleteContact
};
})();
这是我的HTML代码
<button class = "create">Create contact</button>
<form align=center id="createForm">
<br><input placeholder="First Name" id="firstName" /><br><br>
<input placeholder="Last Name" id="lastName" /><br><br>
<input placeholder="Phone number" id="number" /><br><br>
<input placeholder="Email Address" type="email" id="email" /><br><br>
<input id="addButton" type="submit" value="CREATE" /><br><br>
</form>
<div class = "search">Search contacts</div>
<table id="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>Email Address</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
答案 0 :(得分:1)
唯一的区别是
<form align=center id="createForm" onsubmit="return false">