简体   繁体   English

如何检查两个jQuery选择器是否选择了相同的元素

[英]How to check if two jQuery selectors have selected the same element

Is there a way for me to progamatically determine if two jQuery selectors have selected the same exact element? 有没有办法让我通过progamatically确定两个jQuery选择器是否选择了相同的元素? I am trying to loop over a set of divs and skip one of them. 我试图循环一组div并跳过其中一个。 What I would like is something like this: 我想要的是这样的:

var $rows, $row, $row_to_skip;
$rows = $('.row-class')
$row_to_skip = $('#skipped_row')

$.each($rows, function (id, row) {
        $row = $(row);
        if (!$row == $row_to_skip) {
            // Do some stuff here.
        };
    });

You can pass jQuery objects into .not() : 您可以将jQuery对象传递给.not()

$rows.not($row_to_skip).each(function() {
    ...
});

You can use .is() 你可以使用.is()

if (!$row.is($row_to_skip)) {
            // Do some stuff here.
   };

You can compare the actual DOM element selected by jQuery: 您可以比较jQuery选择的实际DOM元素:

var row_to_skip = $row_to_skip.get(0);
$.each($rows, function (id, row) {
    if (row !== row_to_skip) {
        // Do some stuff here.
    }
});

Two jQuery objects will always be different from each other, even if they select the same elements (just like two empty objects are different). 两个jQuery对象总是彼此不同,即使它们选择相同的元素(就像两个空对象不同)。

However in your case, instead of comparing inside the loop, it's cleaner to just remove the element from the set: 但是在你的情况下,不是在循环内部进行比较,只需从集合中删除元素即可:

$('.row-class').not("#skipped_row").each(function() {
    // do stuff 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM