解释Jquery的回报

时间:2014-11-19 09:03:26

标签: javascript jquery function return

给出以下HTML代码:

<ul>
  <li><strong>list</strong> item 1 - one strong tag</li>
  <li><strong>list</strong> item <strong>2</strong> -
    two <span>strong tags</span></li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
  <li>list item 6</li>
</ul>

以及以下jQuery代码:

$( "li" )
  .filter(function( index ) {
    return $( "strong", this ).length === 1; //this line
  })
    .css( "background-color", "red" );

很难理解return语句在这里做了什么。 return语句是否真的意味着以下内容?

if ($( "strong", this ).length === 1){
      return true ;
}else {
     return false ; 
}

我的解释是否正确?

我在jQuery docs页面上找到了这个例子并经历了一些SO帖子,但没有什么能真正解决我的问题。

我创建了fiddle here

编辑:也是一个补充问题:

再次给出相同的代码块:

$( "li" )
  .filter(function( index ) {
    return $( "strong", this ).length === 1; //this line
  })
    .css( "background-color", "red" ); 

如果以下声明:

return $( "strong", this ).length === 1; //this line

返回false,然后是使用Jquery Chaining I.E“链接”的下一个代码块。

.css( "background-color", "red" );

不会执行。我是对的吗?

1 个答案:

答案 0 :(得分:0)

===是一个逻辑运算符,因此它返回一个bool值 所以你可以做到

return $( "strong", this ).length === 1;

而不是

if($( "strong", this ).length === 1){
    return true;
}else{
     return false;
}

编辑:

filter方法用于选择所需的“li”列表。

所以我认为如果$( "strong", this ).length === 1为false,则当前this li将不在列表中。 然后,它将对列表中的所有css执行li方法。