在下面的代码中,为什么postCodes[i].countryCode
会返回循环中的最后一个值,
而不是循环中的当前值?
以及如何在循环中返回当前值?
for (var i = 0; i < postCodes.length; i++) {
for (var ind = 0; ind < salesSuite.Defaults.Countries.length; ind++) {
if (postCodes[i].countryCode == myNamespace.Countries[ind].code) {
$('<button/>')
.click(function () {
console.log(postCodes[i].countryCode);
})
.appendTo($modalContent);
最佳答案
尝试添加一个函数来获取一个处理程序,该处理程序创建一个局部变量来保存该 postCode
。当然,这样做的原因是在处理程序中使用了共享变量 i
,该变量在调用处理程序时已经用完了所以最终在您的处理程序中您试图调用 postCodes [postCodes.length].countryCode
与 undefined.countryCode
相同,将抛出错误..
$('<button/>')
.click(getHandler(postCodes[i]))
.appendTo($modalContent);
.....
.....
function getHandler(postCode){
// This function creates a closure variable postCode which will hold that particular postCode passed in for each invocation to be used in the function reference returned by this
return function () {
console.log(postCode.countryCode);
}
}
您可以利用 jquery data api 来保存邮政编码,而不是执行所有这些操作。
$('<button/>')
.click(function () {
console.log($(this).data('postCode').countryCode);
})
.appendTo($modalContent).data('postCode', postCodes[i]);
关于javascript - 使用对象的值添加 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433532/