我有一个看起来像这样的 json:
contacts = [{"id":"0001","title":"Mr","name_first":"Bob","name_last":"Edwards","address1":"2 ford road","address2":null,"address3":null,"town":"Bedford","county":"Bedfordshire","postcode":"Mk16hd","telephone1":"01827485999","telephone2":null,"email":"bob@email.com"},
{"id":"8003","title":"Mr","name_first":"Joe","name_last":"Bloggs","address1":"186 Bath Road","address2":null,"address3":null,"town":null,"county":null,"postcode":null,"telephone1":"01827485648","telephone2":null,"email":"joe@email.com"},
{"id":"R005","title":"Mr","name_first":"Foo","name_last":"Bar","address1":null,"address2":null,"address3":null,"town":null,"county":null,"postcode":null,"telephone1":"01827485647","telephone2":null,"email":"foo@email.com"}];
然后我像这样循环,为每个按钮创建一个按钮:
for (var key in contacts) {
if (contacts.hasOwnProperty(key)) {
var contact = contacts[key];
var button = document.createElement('button');
button.innerHTML = '<span class="left-body">Edit</span>';
button.onclick = function() { editContact(key); return false; };
}
}
单击每个按钮时,我得到“扩展”一词作为函数中索引的值editContact()
:
function editContact (index) {
console.log(index);
return false;
}
问:这是什么?如何设置才能将每个 json 项的密钥放入editContact()
函数中?