简体   繁体   中英

Target child of <li> element

I am trying to create a check list. When you click on the li element, the child div of that element should become visible.

<div id="list_one">
    <h2>LIST TITLE</h2>
    <div id="line"></div>
    <ul>
        <li id="1-1"><div class="blue_line"></div><div class="circle"></div>TASK ONE</li>
        <li id="1-2"><div class="blue_line"></div><div class="circle"></div>TASK TWO</li>
        <li id="1-3"><div class="blue_line"></div><div class="circle"></div>TASK THREE</li>
        <li id="1-4"><div class="blue_line"></div><div class="circle"></div>TASK FOUR</li>
        <li id="1-5"><div class="blue_line"></div><div class="circle"></div>TASK FIVE</li>
        <li id="1-6"><div class="blue_line"></div><div class="circle"></div>TASK SIX</li>
    </ul>
</div>

Here is my Javascript:

$(document).ready(function() {
    $(".blue_line").css("visibility","hidden");

    $("li").click(function() {
        var id = this.id;
        console.log(id);
        $(id).children().css("visibility","visible");
    });
});

You do not need to use the id like that. Use $(this) to access the LI:

$(document).ready(function() {
    $(".blue_line").css("visibility","hidden");
    $("li").click(function() {
        $(this).children().css("visibility","visible");
    });
});

As pointed out elsewhere, the cause was using $(id) when you needed to do $('#' + id) to make it a valid jQuery ID selector

You have to include the # character:

$(document).ready(function() {
    $(".blue_line").css("visibility","hidden");
    $("li").click(function() {
        var id = this.id;
        console.log(id);
        $("#" + id).children().css("visibility","visible");
    });
});

But as already mentioned, it makes much more sense to use $(this) within the event:

$(document).ready(function() {
    $(".blue_line").css("visibility","hidden");
    $("li").click(function() {
        $(this).children().css("visibility","visible");
    });
});

Note sure if I got you right but:

$("li").on('click', function() {
    $(this).toggleClass('checked');
});

Fiddle: http://jsfiddle.net/C6Qav/1/

"When an item is clicked add a checked class which shows a blue line".

It is nicer that way - less intrusive to use a class and you can do anything you want in the css file to the li element when it has the .checked class (not adding styles directly with javascript to the element is recommended).

PS Avoid using IDs everwhere.

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