2010-10-30 68 views
1

我试图创建一个简单的按钮管理器中选择并最终取消选择媒体链接检查其中包含CSS类.my_classimg元素,为什么不起作用?jQuery的:检查元素是否被分配给一个变种

var last_selected; 
$("img.my_class").click (function() { 
    if (last_selected != null) alert ($(this) == last_selected); // returns false everytime 
    last_selected = $(this); 
}); 

回答

0

每次包装this时,都会创建一个新的jQuery对象。两个jQuery对象不相等,仅仅因为它们包装了相同的元素($(this) != $(this))。

相反,将this本身分配给last_selected,并且所有内容都应按预期工作。

var last_selected; 
$("img.my_class").click (function() { 
    if (last_selected != null) alert (this == last_selected); 
    last_selected = this; 
}); 
+0

应该在比较中使用'==='。 – Pointy 2010-10-30 13:00:49

+0

它的工作原理,感谢您的帮助 – vitto 2010-10-30 13:29:21

+0

你介意给我一个这里的手:http://stackoverflow.com/questions/4532009/placing-error-message-for-a-checkbox-array ?? – eddy 2010-12-26 17:59:07

1

它不起作用,因为每次调用$(this)时都会创建一个新的jQuery包装器对象。

相反,尝试只是节省“这个”:

var last_selected; 
$("img.my_class").click (function() { 
    if (last_selected != null) alert (this === last_selected); 
    last_selected = this; 
}); 
1

为什么不分配“选择”级到当前选定的IMG?

$('img.my_class').click(function() 
{ 
    // remove the selected class from the previous selected 
    $('img.my_class.selected').removeClass('selected'); 
    // flag the current one as selected 
    $(this).addClass('selected'); 
}); 
相关问题