문제

I need to be able to have a variable that identifies that position of an li, using .index() and then assigns a value to it depending on the variable number for each individual li.

This may sound a little confusing, so I've written a jsfiddle to explain it all a little better. There are 3 lis, and when I click a button/link, I need them all to spread out based on their :nth-child position, using position: absolute. However, the problem I have at the moment is that the variable (itemNumber) is the same and not changing for every li.

Here is my code:

<ul>
    <li>Lorem Ipsum 1</li>
    <li>Lorem Ipsum 2</li>
    <li>Lorem Ipsum 3</li>
</ul>
<a href="#">Click me</a>

and JS:

var itemNumber = $("ul li").index() + 1;

 $("a").click(function () {
     $("ul").toggleClass("expanded");
     $("ul li").each(function () {
         $("ul li:nth-child(" + itemNumber + "n)").css("top", itemNumber * 30 + "px");
     });
 });

I'll be happy to explain it more because the idea is a little confusing. The basic premise is, I need the variable itemNumber to change for each li, and there could be any number of lis.

도움이 되었습니까?

해결책

You can try this -

$("ul li").each(function (index,element) {
         $("ul li:nth-child(" + index + "n)").css("top", index * 30 + "px");
});

Or better

$("ul li").each(function (index,element) {
         $(this).css("top", index * 30 + "px");
});

다른 팁

Use .eq instead:

var itemNumber = $("ul li").index(); // eq is 0 based index

$("ul li").each(function (i, v) {
         $("ul li").eq(itemNumber).css("top", (itemNumber + 1) * 30 + "px");
     });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top