jQuery:检查是否将元素分配给变量 [英] jQuery: Check if an element is assigned to a var
本文介绍了jQuery:检查是否将元素分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个简单的按钮管理器,以选择并最终取消选择所有已检查的包含CSS类.my_class
的img
元素,为什么它不起作用?
I'm trying to create a simple button manager to select and eventually unselect allready checked img
elements which contains CSS class .my_class
, why this doesn't work?
var last_selected;
$("img.my_class").click ( function () {
if (last_selected != null) alert ($(this) == last_selected); // returns false everytime
last_selected = $(this);
});
推荐答案
每次包装this
时,都会创建一个新的jQuery对象.两个jQuery对象彼此不相等,只是因为它们包装了相同的元素($(this) != $(this)
).
Each time you wrap this
you create a new jQuery object. Two jQuery objects are not equal to each other just because they wrap the same element ($(this) != $(this)
).
相反,将this
本身分配给last_selected
,一切都应按预期工作.
Instead, assign this
itself to last_selected
and everything should work as expected.
var last_selected;
$("img.my_class").click ( function () {
if (last_selected != null) alert (this == last_selected);
last_selected = this;
});
这篇关于jQuery:检查是否将元素分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文