jQuery objects of the same element are not equal?

前端 未结 5 1591
梦毁少年i
梦毁少年i 2021-01-17 23:39

This must be something I\'m overlooking, but please look at the following page and JavaScript and tell me why, for everything that\'s holy, jQuery won\'t return true?

<
相关标签:
5条回答
  • 2021-01-18 00:07

    You can use the jQuery is method.

    Description: Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

    if (t.is(s)) {
        console.log('yes');
    }
    

    Example fiddle: http://jsfiddle.net/IrvinDominin/q86Sh/

    0 讨论(0)
  • 2021-01-18 00:08

    You could do this, a comparison of the HTML nodes. Which if you want to compare HTML objects is the correct way to do it.

    if (t[0] === s[0]) {
        console.log('yes');
    }
    
    0 讨论(0)
  • 2021-01-18 00:18

    You had your script in the <head> but the element <p class="test">hello1</p> in <body>.

    First you should use $(document).ready() to make sure the content is loaded. Then check if they are equal using .is().

    $(document).ready(function() {
    
            var t = $('.test');
            var s = $('.test');
    
            console.log(t);
            console.log(s);
    
            if (t.is(s)) {
                console.log('yes');
            }
    });
    

    Compare the examples with and without the .ready() function.

    0 讨论(0)
  • 2021-01-18 00:22

    This could help you:

    var test = document.getElementById('test') //returns a HTML DOM Object
    var test = $('#test') //returns a jQuery Object
    var test = $('#test')[0] //returns a HTML DOM Object
    

    So (like limelights told you) use this:

    if (t[0] === s[0]) {
        console.log('yes');
    }
    

    Also it is good practice to use

    $(document).ready(function(){
    
    
    });
    

    around your code.

    0 讨论(0)
  • 2021-01-18 00:31

    Try this - Working Demo --> http://jsfiddle.net/mohammadAdil/tHjgN/

     if(t.is(s)) {
        console.log('yes');
     }
    

    http://api.jquery.com/is/

    Or with ===

    if (t.get(0) === s.get(0)) { //<--Compare DOM elements instead of jquery object's
        console.log('again yes');
    }
    

    Demo --> http://jsfiddle.net/mohammadAdil/tHjgN/1/

    0 讨论(0)
提交回复
热议问题