次のような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()
関数のインデックスの値として「extend」という単語が表示されます。
function editContact (index) {
console.log(index);
return false;
}
editContact()
Q: これは何ですか? また、各 json アイテムのキーを関数に取得するように設定するにはどうすればよいですか?