jq過濾方法大全

過濾就是從匹配元素集合中找到想要的元素。(就是從一堆元素中找我們想要的那些)
1.first()和last()
語法:$(selector).first()
獲取匹配元素集合中第一個元素。這個方法不接受任何參數。
語法:$(selector).last()
獲取匹配元素集合中最後一個元素。這個方法不接受任何參數。

<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
</ul>
<p>
    <span>Look:</span>
    <span>This is some text in a paragraph.</span>
    <span>This is a note about it.</span>
</p>
<script>
    $("li").first().css("background-color", "red");
    $("p span").first().addClass('highlight');
</script>

2.filter()和not()和has()
filter: 把需要的過濾出來
not: filter的反義詞,把不需要的過濾出來
has:包含

 <ul id="list">
        <li> <span class="a">我是span</span> 111111</li>
        <li class="a">2222222</li>
        <li>33333333</li>
        <li class="b">4444444</li>
        <li class="a">5555555555</li>
    </ul>

    <script>
        // $("#list li").css("background-color",'red'); // 所有li都會變
        // $("#list li").filter('.a').css("background-color",'red'); // 帶.a的li會
        // $("#list li").not('.a').css("background-color",'red'); // 不帶.a的li
        $("#list li").has('.a').css("background-color",'red'); // 子元素中有帶.a的li
    </script>

3.eq()
下標從0開始

    <h1>我是標題00000</h1>
    <div class="box">
        <p>111111</p>
        <p>2222</p>
        <div>
            <p>333</p>
        </div>
        <p class="selected">444444</p>
        <h1>我是標題1111</h1>
    </div>

    <script>
        $("h1").eq(1).css('color','blue')
        $(".box").find("p").eq(3).css('color','red')
    </script>
    4.index()方法

索引就是當前元素在所有兄弟節點中的位置,從0開始(就是當前元素在一組元素中的位置,當前元素和這一組元素是平級的兄弟關係)


<div>
    <h1>11111</h1>
    <h2>222222222</h2>
    <h1>333333333</h1>
    <h2 id="hhh">444444444444</h2>
    <h1>555555555555</h1>
    <p>666666666</p>
</div>
<h2>7777777777</h2>
<script>
    $(function(){
        alert($('#hhh').index()); // 3
    });
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章