在 Jquery 中解释返回

interpreting return in Jquery

本文关键字:返回 解释 Jquery      更新时间:2023-09-26

给定以下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文档页面上找到了这个例子,并浏览了一些SO帖子,但没有真正解决我的问题。

我在这里创建了一个小提琴

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

所以再次给定相同的代码块:

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

如果以下语句:

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

返回 false,然后下一个使用 Jquery 链接"链接"的代码块。

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

不会执行. 我说得对吗?

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

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

而不是

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

对于编辑:

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

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