jquery中filter方法用法实例分析

  本文实例讲述了jquery中filter方法用法。分享给大家供大家参考。具体分析如下:

  filter()方法将匹配元素集合缩减为匹配指定选择器的元素。

  filter方法中的参数可以为字符串值,包含供匹配当前元素集合的选择器表达式。

  一、filter的参数类型可分为两种

  

  1、传递选择器

  $('a').filter('.external')

  2、传递过滤函数

  

复制代码 代码如下:
$('a').filter(function(index) {

  return $(this).hasClass('external');

  })

  二、Jquery中find与filter区别

  1、find()会在div元素内 寻找 class为classname的元素。

  2、filter()则是筛选div的class为classname的元素。

  3、基本是find子元素找,filter是平级找

  4、find 函数是在当前对象集合的子元素中进行查询;

  5、filter 函数是对当前对象集合进行过滤, 利用过滤条件缩小范围;

  6、find 函数的参数是 jQuery 选择器表达式;

  7、filter 的参数也是选择器表达式, 但可以有多个条件, 用逗号分隔(逻辑或关系);

  8、filter 的参数也可以是个函数, 调用函数时会自动传入 index 参数, 函数需返回 true或false 以选中或排除元素.

  例如:

  

复制代码 代码如下:
<!DOCTYPE>

  <html>

  <head>

  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">

  <title>Document</title>

  <script>

  $(function(){

  $('#btn1').click(function(){

  alert($('div').find('.test').html());

  });

  $('#btn2').click(function(){

  alert($('div').filter('.test').html());

  });

  $('#btn3').click(function(){

  alert($('div').filter('.last').html());

  });

  $('#btn4').click(function(){

  alert($('div').filter('.first,.last').html());

  });

  });

  </script>

  </head>

  <body>

  <input type="button" value="test-find" id="btn1" />

  <input type="button" value="test-filter" id="btn2" />

  <input type="button" value="test-filter" id="btn3" />

  <input type="button" value="test-filter" id="btn4" />

  <div class="first">first content<span class="test">test content</span></div>

  <div class="last">last<span class="test">last test content</span></div>

  <div class="last">last<span>last no test content</span></div>

  </body>

  </html>

  希望本文所述对大家的jQuery程序设计有所帮助。