jQuery .attr 函数未正确返回
我正在构建一个带有复选框的列表,创建列表后,我使用“.each”来遍历它们并尝试应用单击过程。
我的代码像这样工作正常:
$.ajax({
url: "./views/todoitems.view.php",
data: "cmd=list",
success: function(html){
$('#list-container').empty().append(html);
$('input:checkbox').each(function(){
$check = $(this);
$check.click(function(){
alert($(this).attr('itemid'));
});
});
}
});
但是,一旦我将警报更改为,
alert($check.attr('itemid'));
无论单击哪一项,它都只显示列表中最后一项的 id。 我究竟做错了什么?
I am building a list with checkboxes, after the list is created I am using ".each" to go through them all and trying to apply a click procedure.
My code like this works fine:
$.ajax({
url: "./views/todoitems.view.php",
data: "cmd=list",
success: function(html){
$('#list-container').empty().append(html);
$('input:checkbox').each(function(){
$check = $(this);
$check.click(function(){
alert($(this).attr('itemid'));
});
});
}
});
However, as soon as I change the alert to be
alert($check.attr('itemid'));
It only ever shows the id of the last item in the list no matter which one is clicked.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$check 在每个处理程序内部设置,并且是一个全局变量。 这意味着它将保留最后设置的值,即最后一个复选框。 如果您想正确执行此操作,则需要将其设置在单击处理程序中。 将其更改为:
注意: 上面使用
var
来控制范围。此外,您不需要为此使用
each()
。 这是等价的:$check is set inside the each handler and is a global variable. That means it'll retain the last value set, being the last checkbox. You need to set it inside the click handler if you want to do it right. Change it to:
Note:
var
is used above to control scope.Also, you don't need to use
each()
for this. This is equivalent:添加到 cletus 的答案(我还不能发表评论) $check 正在成为隐含的全局变量,因为它的声明缺少 var。
To add to cletus' answer (I can't comment yet) $check is becoming an implied global variable because its declaration is missing var.