开发者

Check if objects within a variable are also contained in another variable (jQuery)

开发者 https://www.devze.com 2023-04-05 01:34 出处:网络
I hope the title somewhat sums up what I am trying to achieve. Let\'s say I have two variables: var one = $(\'div.foo, div.faa, div.fee, span, a, .all-sorts-of-开发者_运维百科objects\'),

I hope the title somewhat sums up what I am trying to achieve.

Let's say I have two variables:

var one = $('div.foo, div.faa, div.fee, span, a, .all-sorts-of-开发者_运维百科objects'),
    two = $('div.fii, div.foo, span, .all-sorts-of-objects-two');

And now, I want to check if objects contained within two are also contained within one. In other words, if there are any objects within both variables.

I need this so that I can set-up a non-overriding hover function (i.e. because I'm adding inline color-styles, I need to target my objects wisely). This is the logic I came up with: (note the if(one == two) which is essentially my question).

one.hover(function() {
    if(one == two) { // if there is one or more objects in both variables..
       $(this).css('color', 'red');
    } else {
       $(this).css('color', 'blue');
    } 
}, function() {
    // ...
});

I hope I have been clear enough. If not, please let me know and I will do my best to explain this better.

Thank you very much!


Here is a quick and dirty way to do it:

var one = $('div.foo, div.faa, div.fee, span, a, .all-sorts-of-objects').addClass('one');
var two = $('div.fii, div.foo, span, .all-sorts-of-objects-two').addClass('two');

one.hover(function() {
    if(one.hasClass('two')) {
       $(this.css('color', 'red');
    }
});


In my book the cleanest way (apart from refactoring to avoid these duplicate selectors if possible) would be to use the merge and unique jQuery utilities, something like:

var $merged = $.merge(one, two);
var $unique = $.unique($merged.get());

The $unique now has the unique, or, if you like, distinct elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号