jQuery -如何检查两个元素是否相同

jQuery - how to check if two elements are the same?

本文关键字:元素 两个 是否 何检查 检查 jQuery      更新时间:2023-09-26

我需要将一个元素传递给一个函数,然后在遍历父元素时匹配该特定元素。问题(对于像我这样无知的人来说)是这个元素没有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));
});

比较JQuery对象永远不会返回true,因为每个JQuery对象都是一个新对象,即使它们的选择器是相等的。

要比较元素,必须检查DOM元素是否相等:

this === element.get(0);

可以使用jQuery的is()函数。原始答案可在此处找到。

function colorize(element) {
    element.parent().find('span').each(function() {
        if ( $(this).is(element) ) {
            $(this).css('background','yellow');
        } else {
            $(this).css('background','pink');
        }
    });
}

使用isEqualNode检查两个元素是否具有相同的标记

this.isEqualNode(element)

或者使用isSameNode检查两个元素是否为相同的DOM节点

this.isSameNode(element)

你不必这么做。你总是在一个特定的元素上应用特殊的样式,所以把它们都涂上颜色,然后改变特定元素的颜色。

function colorize(element) {
    element.parent().find('span').each(function() {
        $(this).css('background','pink');
    });
    element.css('background','yellow');
}

你比较的问题是你比较两个对象(jQuery对象)。在比较对象时,除非它们指向相同的对象,否则它们被认为是不相等的:

var o1 = {};
var o2 = {};
o1 !== o2;

你可以通过移除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');
        }
    });
}

这样,您将比较DOM元素与DOM元素,而不是苹果与橘子或对象与对象。