How to select a range of elements in jQuery

后端 未结 3 891
庸人自扰
庸人自扰 2020-11-28 08:57
... ... ... ... ...
相关标签:
3条回答
  • 2020-11-28 09:32

    You should be able to do this by extracting a slice of the array thus. It's the line

    $("div[id='myDiv'] > a").slice(1,4).css("background","yellow");
    

    that you're interested in. It will affect the 2nd, 3rd and 4th elements.

    <html>
        <head>
            <script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
            <script type="text/javascript">
                $(document).ready(function(){
                    $("a").click(function(event){
                        $("div[id='myDiv'] > a").slice(1,4).css("background","yellow");
                        event.preventDefault();
                    });
                });
            </script>
        </head>
        <body>
            <div id="myDiv">
                <a>1</a>
                <a>2</a>
                <a>3</a>
                <a>4</a>
                <a>5</a>
                <a>6</a>
            </div>
            <hr>
            <a href="" >Click here</a>
            <hr>
        </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 09:35

    Using the .slice() function does exactly what I need.

    0 讨论(0)
  • 2020-11-28 09:38

    jQuery slice() function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself.

    In your particular case you should use

    $("#myDiv a").slice(1, 4)
    
    0 讨论(0)
提交回复
热议问题