jQuery-如何检查两个元素是否相同? [英] jQuery - how to check if two elements are the same?

查看:1316
本文介绍了jQuery-如何检查两个元素是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个元素传递给函数,然后在遍历父元素时匹配该特定元素。问题是(对于像我这样笨拙的人)这个元素没有ID。在下面的示例中,我希望每个元素都变为粉红色,但单击的元素应变为黄色

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

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

Comparing JQuery objects will never return true, because each JQuery object is a a new object, even if their selectors are equal.

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

To compare elements, you have to check whether the DOM elements are equal:

this === element.get(0);

这篇关于jQuery-如何检查两个元素是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆