JQuery functions: eq () ,: lt () and: gt (), which do not provide the expected results

I use jQuery's eq () functions, but it doesn't give the correct results

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div p:eq(1)").css("border","2px solid red");

    });
});
</script> 
</head>
<body>
    <button>Click Me!</button>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <div>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
    </div> 
    <div>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
    </div> 
</body>
</html>

Expectation:

I expected 2 lines to be red (5 and 8).

Result:

enter image description here

Also, when I use lt (), I get the wrong results.

HTML:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div p:lt(2)").css("border","2px solid red");

    });
});
</script> 
</head>
<body>
    <button>Click Me!</button>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <div>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
    </div> 
    <div>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
    </div> 
</body>
</html>

Expectation:

I expected 4 lines to be red (6, 7, 11 and 12).

Result:

enter image description here Note:

I know that as an alternative, I can use nth-child () or nth-of-type (), nth-last () or nth-last-child (), or: odd () or: even (); or: nextAll () or: prevAll (), but I want to know why this does not work !; (.

Can someone help me where the problem is?

+4
source share
3 answers

. , , , , , . 1

div p:eq(1) div p. , :eq() ( , ). .

div p:lt(2) div p. , .

p div, .each() div .find('p:eq(1)') .find('p:lt(2)') . div p:nth-child(2) div p:nth-child(-n+2) jQuery .


1 - , .

+4

jQuery "div p" 6 p- 2 div. eq(1) 6 , .

div,

var items=$("div");
$.each(items,function(a,b)
{
    $(b).find("p").eq(1).css("border","2px solid red"); 
});

, $(b).find( "p" ), 3 p- , , eq(1), .

-

+1

nth-child() jquery, css:

, nth-child . (..) n "1-", , 1. , : eq() : jQuery "0-indexed" JavaScript. <ul>, <li> s, $( "li:nth-child(1)" ) <li>, $( "li:eq(1)" ) .

. : http://api.jquery.com/nth-child-selector/

0

Source: https://habr.com/ru/post/1621715/


All Articles