javascript jQuery 比较两个 DOM 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15197477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:50:20  来源:igfitidea点击:

jQuery compare two DOM object?

javascriptjquerydomobjectcompare

提问by Zbarcea Christian

Clicking on an element:

单击一个元素:

$('.my_list').click(function(){
   var selected_object = $(this);

   $('.my_list').each(function(){
      var current_object = $(this);

      if( selected_object == current_object ) alert('FOUND IT !');
   });
});

I don't know why, but I don't get the alert message "FOUND IT !".

我不知道为什么,但我没有收到警报消息“找到了!”。

回答by Salman A

You can use the jQuery.isfunction:

您可以使用该jQuery.is功能:

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

根据选择器、元素或 jQuery 对象检查当前匹配的一组元素,如果这些元素中至少有一个与给定的参数匹配,则返回 true。

if (selected_object.is(current_object)) {
   ...    
}

An alternate solution is to use jQuery.getfunction to get the raw elements and compare them using ==or ===operator:

另一种解决方案是使用jQuery.getfunction 获取原始元素并使用==or===运算符比较它们:

if (selected_object.get(0) == current_object.get(0)) {
   ...
}

jsFiddle demo

jsFiddle 演示

回答by Farside

There's good answer provided... but it's important to understand, why you directly can't compare selectors in jQuery.

提供了很好的答案......但重要的是要理解,为什么你不能直接比较 jQuery 中的选择器。

jQuery selectors return data structures which will never be equalin the sense of reference equality. So the only way to figure this out is to get DOM reference from the jQuery object and to compare DOM elements.

jQuery 选择器返回的数据结构在引用相等的意义上永远不会相等。所以解决这个问题的唯一方法是从 jQuery 对象获取 DOM 引用并比较 DOM 元素。

The simplest comparison of DOM reference for the above example would be:

上面示例的 DOM 引用的最简单比较是:

selected_object.[0] == current_object.[0]