gpt4 book ai didi

javascript - 在 for-in 循环中传递按钮单击事件上的键时获取单词 "extend"

转载 作者:行者123 更新时间:2023-12-02 18:46:56 27 4
gpt4 key购买 nike

我有一个如下所示的 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;
}

问:这是什么?如何设置它以便将每个 json 项目的 key 获取到 editContact() 函数中?

最佳答案

因为关闭了

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(key){
return function() { editContact(key); return false; };
})(key);
}
}

演示:Fiddle

关于javascript - 在 for-in 循环中传递按钮单击事件上的键时获取单词 "extend",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16276676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com