jquery中filter方法用法實(shí)例分析

字號:


    這篇文章主要介紹了jquery中filter方法用法,實(shí)例分析了filter方法的功能并對比了與find方法的區(qū)別,需要的朋友可以參考下
    本文實(shí)例講述了jquery中filter方法用法。分享給大家供大家參考。具體分析如下:
    filter()方法將匹配元素集合縮減為匹配指定選擇器的元素。
    filter方法中的參數(shù)可以為字符串值,包含供匹配當(dāng)前元素集合的選擇器表達(dá)式。
    一、filter的參數(shù)類型可分為兩種
    1、傳遞選擇器
    $('a').filter('.external')
    2、傳遞過濾函數(shù)
    代碼如下:
    $('a').filter(function(index) {
    return $(this).hasClass('external');
    })
    二、Jquery中find與filter區(qū)別
    1、find()會在div元素內(nèi) 尋找 class為classname的元素。
    2、filter()則是篩選div的class為classname的元素。
    3、基本是find子元素找,filter是平級找
    4、find 函數(shù)是在當(dāng)前對象集合的子元素中進(jìn)行查詢;
    5、filter 函數(shù)是對當(dāng)前對象集合進(jìn)行過濾, 利用過濾條件縮小范圍;
    6、find 函數(shù)的參數(shù)是 jQuery 選擇器表達(dá)式;
    7、filter 的參數(shù)也是選擇器表達(dá)式, 但可以有多個條件, 用逗號分隔(邏輯或關(guān)系);
    8、filter 的參數(shù)也可以是個函數(shù), 調(diào)用函數(shù)時會自動傳入 index 參數(shù), 函數(shù)需返回 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>first content<span>test content</span></div>
    <div>last<span>last test content</span></div>
    <div>last<span>last no test content</span></div>
    </body>
    </html>
    希望本文所述對大家的jQuery程序設(shè)計有所幫助。