Javascript / jQuery将不同的函数args附加到.click()方法 [英] Javascript/jQuery attach different function args to .click() method
问题描述
这段代码有什么问题?读这个似乎对于每个循环,jquery应该为每个迭代附加一个具有赋值的函数。相反,它将i = 2附加到每个对象。为什么这样做,如何让它附加预期的值(例如,0,1,......)?
What's wrong with this code? Reading this it seems that for each loop the jquery should attach a function with assigned values for each iteration. Instead it's attaching i = 2 to every object. Why is it doing that and how can I get it to attach the expected values (e.g., 0, 1, ...)?
//data.length is 2.
for (i=0; i<data.length; i++) {
// Attach the click function
linkId = 'a#' + pk;
$(linkId).click(function(e) {
e.preventDefault();
console.log(i, pk, data);
});
};
console.log - 每个链接都有相同的参数
console.log -- each link has the same parameters
2 "52fef25e391a56206f03be6e" [object Array]
推荐答案
您假设某个块创建了一个新的变量范围。它不是在JavaScript中。只有一个函数执行。
You're assuming that a block creates a new variable scope. It doesn't in JavaScript. Only a function execution does.
如果你使用 $。each()
,你给它的回调将每次迭代都会调用,因此每个迭代都会有一个新的范围。
If you use $.each()
instead, the callback you give it will be invoked for each iteration, and so you'll have a new scope for every one.
$.each(data, function(i,item) {
// ^---^---function parameters are local to this scope
// v--declare a variable local to this scope
var linkId = 'a#' + pk;
// v--the function made in this scope can access the local vars
$(linkId).click(function(e) {
e.preventDefault();
console.log(i, pk, data, linkId, data[i]);
});
});
这篇关于Javascript / jQuery将不同的函数args附加到.click()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!