过滤方法jQuery

时间:2012-09-13 17:14:25

标签: javascript jquery-plugins javascript-events jquery

请使用以下代码帮助我。我不明白。我必须在我的项目中使用这样的代码片段。

$('strong', this) < - 这一部分对我来说根本不清楚。

如果可能的话,请务必逐行解释整个代码。

<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>

JavaScript的:

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

由于

2 个答案:

答案 0 :(得分:1)

$('strong', this)是jQuery选择器,格式为$(target, context)

根据你的代码:

this表示li,而$('strong', li)正在<strong>标记内搜索li

此声明也可以写成:

$(this).find('strong')从jQuery库代码中你会看到:

$(target, context)格式在内部实现

$(context).find(target)进程。

For more see here

答案 1 :(得分:1)

代码基本上是使用jQuery $('li')获取li元素列表(这将获取页面上的所有<li> ... </li>标记) 然后使用.filter函数减少此集合,filter将函数作为参数,在列表中的每个元素上调用该函数,如果返回true,则从过滤器返回列表中的元素如果返回false,则忽略该项。

在此上下文中,函数调用$('strong', this).length == 1,其中this是过滤器当前正在决定检查的li标记,如其他答案所述,它只是检查返回<strong>..</strong>列表当前li中的标签。如果当前li中没有强,则length为0,因此函数返回false,这意味着过滤器不会在它生成的列表中返回该元素,然后继续前进到下一个li。

这意味着代码的第一部分只生成一个带有强标记的li列表,然后将其与css函数链接,将所有这些标记用红色着色。

希望有所帮助。