简体   繁体   中英

How to get previous <li> when the li's are wrapped inside <ol>?

How do i get the previous li when it is wrapped inside an ol?

I have used the following script, but it doesnt seem to work:

<script type="text/javascript">
$(document).ready(function () {
    $(".categoryitem").click(function () {
        alert("hihi");
        $(this).parent().prev("li").css('background-color', 'red');
        $(this).prev("li").css('background-color', 'red');       
    });
});
</script>

This is how the HTML looks like (In my real application i have set the class name on each li, but didnt do it in this example)

<ul>
<li>
<a href="">Item 1</a>
</li>
<ol>
<li>
<a href="">Item 1.1</a>
</li>
</ol>
<li>
<a href="">Item 2</a>
</li>
<ol>
<li>
<a href="">Item 2.1</a>
</li>
<ol>
<li>
<a href="">Item 2.1.1</a>
</li>
</ol>
<ol>
<li>
<a href="">Item 2.1.2</a>
</li>
</ol>
<ol>
<li>
<a href="">Item 2.1.3</a>
</li>
</ol>
<ol>
<li>
<a href="">Item 2.1.4</a>
</li>
</ol>
</ol>
</ul>

When i click on Item 1.1, the parent 1 becomes red When i click on item 2, nothing happens, but i would like 1.1 to become red When i click on items 2.1.1, 2.1.2, 2.1.3, 2.1.4 nothing happens When i click on item 2.1, the parent 2 becomes red

I would like all previous LI's to become red, even if they are in higher levels

What am i doing wrong?

This is the method that creates the tree: EDIT: I changed ol to ul, for each group

<ul>
@{
    foreach(var cq in Model) {
        @ShowSubItems(cq);
    }
}
</ul>

@helper ShowSubItems(MvcApplication3.Models.ViewModels.Category.AllQuestionsInCategoriesViewModel MyObj)
    {

    <li class="categoryitem" categoryid="1">@Html.ActionLink(MyObj.Category_Number + " " + MyObj.Category_Name, "DisplayQuestions", new { categoryId = MyObj.Category_ID, page = 1 })</li>



        if (MyObj.SubCategories != null && MyObj.SubCategories.Count != 0)
        {
<ul>
            @foreach (var subitem in MyObj.SubCategories)
            {

            @ShowSubItems(subitem)

            }
</ul>
        }
}
</ul>

To get the CLOSEST PARENT, you can simply use .closest()

<ul>
    <li>
        <a href="javascript:void(0);" class="clickme">Click Me!</a>
    </li>
</ul>

$(document).ready(function() {
    $('a.clickme').click(function() {
        $(this).closest('li').css('background-color', 'red');
    });
});

Here's the jsfiddle source of this example: http://jsfiddle.net/y36qg/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM