JQuery Multiple selectors, $(this) reference?

后端 未结 3 724
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 07:56

given the following

$(\"#identifier div:first, #idetifier2\").fadeOut(300,function() {
  // I need to reference just the \'#identifier div:first\' element
           


        
相关标签:
3条回答
  • 2021-01-18 08:00

    No, it'll call the function for each handle separately.

    The comma in your selector is equivalent to saying:

    $("#identifier div:first").fadeOut(300,function() {
      // $(this) -> '#identifier div:first'
      });
    
    $("#idetifier2").fadeOut(300,function() {
       // $(this) -> '#identifier2'
    });
    

    You can check by saying (untested):

    $("#identifier div:first, #idetifier2").fadeOut(300,function() {
      if($(this).is("#identifier div:first")  {
         // do something
      }
    });
    

    However, if you want to do different things (as what seems from your post), its better to attach them separately.

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

    What many people don't seem to realize in jQuery is that when there are multiple matched selectors, whatever functions are after the selector list will be called separately one at a time on each individual selector.

    So $("#identifier div:first, #identifier2") will separately match both:

    $("#identifier div:first")
    and
    $("#identifier2")
    

    And, will call the specified fadeOut function and it's handler separately for each match. That means each handler will have it's own this value set to the match the matched selector.

    Internally inside of jQuery, there's a loop like this pseudo code that iterates through all the returned selector matches and calls the next function in the chain for each one:

    for (var i = 0; i < matches.length; i++) {
        jQuery["fadeOut"].call(matches[i], duration, easing, fn);
    }
    

    If you want separate code to be used for the two different matches, then it might be better to just use two separate jQuery statements:

    $("#identifier div:first").fadeOut(300,function() {
        // do stuff for #identifier div:first
    });
    
    $("#identifier2").fadeOut(300,function() {
        // do stuff for #identifier2
    });
    

    If you have a lot of code in the block and it's mostly the same, then you can also branch within one block of common code:

    $("#identifier div:first, #identifier2").fadeOut(300,function() {
        if (this.id != "identifier2") {
            // execute code that only applies to the #identifier match
        }
        // execute rest of common code
    });
    
    0 讨论(0)
  • 2021-01-18 08:12

    Just check about which ID you're currently processing in $(this)

    if(this.id == "identifier"){ //your code goes here }
    
    0 讨论(0)
提交回复
热议问题