Javascript jQuery - 如何检查两个元素是否相同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7703160/
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
jQuery - how to check if two elements are the same?
提问by A-OK
I need to pass an element to a function and then match that specific element while traversing parent. The catch (for someone clueless like me) is that this element doesn't have an id. In the following example, I want every element to turn pink except the one clicked on that should turn yellow
我需要将一个元素传递给一个函数,然后在遍历父元素时匹配该特定元素。问题(对于像我这样一无所知的人)是这个元素没有 id。在下面的例子中,我希望每个元素都变成粉红色,除了点击的那个应该变成黄色
function colorize(element) {
element.parent().find('span').each(function() {
if ($(this)===element) { // the problem is this is always false
$(this).css('background','yellow');
} else {
$(this).css('background','pink');
}
});
}
$('span').click(function() {
colorize($(this));
});
回答by Rob W
Comparing JQuery objects will never return true, because each JQuery object is a a new object, even if their selectors are equal.
比较 JQuery 对象永远不会返回 true,因为每个 JQuery 对象都是一个新对象,即使它们的选择器相等。
To compare elements, you have to check whether the DOM elements are equal:
要比较元素,您必须检查 DOM 元素是否相等:
this === element.get(0);
回答by Nikola Obreshkov
回答by BrunoLM
Use isEqualNode
to check if two elements have the same markup
使用isEqualNode
检查两个元素具有相同的标记
this.isEqualNode(element)
Or use isSameNode
to check if two elements are the same DOM node
或者isSameNode
用来检查两个元素是否是同一个DOM节点
this.isSameNode(element)
回答by Zirak
You don't have to. You're always applying the special style to one specific element, so color them all, and then change the color of the specific element.
你不必。您总是将特殊样式应用于一个特定元素,因此将它们全部着色,然后更改特定元素的颜色。
function colorize(element) {
element.parent().find('span').each(function() {
$(this).css('background','pink');
});
element.css('background','yellow');
}
The problem with your comparison was that you were comparing two objects (jQuery objects). When comparing objects, unless they're pointing to the same thing, they are considered unequal:
您比较的问题在于您正在比较两个对象(jQuery 对象)。比较对象时,除非它们指向同一事物,否则它们被认为是不相等的:
var o1 = {};
var o2 = {};
o1 !== o2;
You can work around this by removing the jQuery wrapper:
您可以通过删除 jQuery 包装器来解决此问题:
function colorize(element) {
var realElement = element[0];
element.parent().find('span').each(function() {
if (this === realElement) {
$(this).css('background','yellow');
} else {
$(this).css('background','pink');
}
});
}
This way, you're comparing DOM elements to DOM elements, and not apples to oranges or objects to objects.
这样,您将 DOM 元素与 DOM 元素进行比较,而不是将苹果与橙子或对象与对象进行比较。