JQuery Multiple selectors,$(this)reference?

时间:2011-08-07 15:06:51

标签: jquery jquery-selectors

给出以下

$("#identifier div:first, #idetifier2").fadeOut(300,function() {
  // I need to reference just the '#identifier div:first' element
  // however $(this) will grab both selectors
});

除了再次调用$(“#identifier div:first”)之外,还有更好的方法吗?

3 个答案:

答案 0 :(得分:5)

不,它会分别为每个句柄调用函数。

选择器中的逗号等同于:

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

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

您可以通过说(未经测试)来检查:

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

但是,如果你想做不同的事情(就像你的帖子中看到的那样),最好单独附加它们。

答案 1 :(得分:3)

许多人在jQuery中似乎没有意识到,当有多个匹配的选择器时,在每个选择器上一次一个地单独调用选择器列表之后的任何函数。

因此$("#identifier div:first, #identifier2")将分别匹配:

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

并且,将为每个匹配单独调用指定的fadeOut函数及其处理程序。这意味着每个处理程序都将其自己的this值设置为匹配匹配选择器。

在jQuery的内部,有一个类似于这个伪代码的循环,它遍历所有返回的选择器匹配并调用链中的下一个函数:

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

如果您希望将单独的代码用于两个不同的匹配,那么最好只使用两个单独的jQuery语句:

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

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

如果块中有很多代码并且它们大致相同,那么您也可以在一个公共代码块中分支:

$("#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
});

答案 2 :(得分:1)

只需检查您当前在$(this)

中处理的ID
if(this.id == "identifier"){ //your code goes here }