简体   繁体   中英

UL LI click is hiding the UL

I am trying to make a UL LI list such that when the word "LIST" is clicked on, the LI elements will be displayed and vice-versa. However, if an LI is clicked on the entire list gets hidden again. I'd like to make it such that if an LI is clicked on, it wont hide my list as I'd like to add functionality for the LI click later.

Here is the code in question:

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    cursor: pointer;
}
ul li {
    display: none;
}
ul li:before{ content:"- ";}
</style>

<script type="text/javascript">

window.onload = function() {

$('ul').click(function(){

     if ($('ul > li').css('display') == 'none') {

        $('ul > li').show();

    }
    else {
    $('ul > li').hide()

    }

});

}
</script>

</head>

<body>

<ul>
    List
    <li>1234</li>
    <li>5678</li>
    <li>0123</li>
</ul>


</body>

</html>

As pointed out above you can't just stick text in a ul like that. A ul should only have li elements within it. A cleaner approach is something like this that shows and hides the ul element instead of all the li s inside it with a control external to the ul .

Also as pointed out below there is a much better way to handle this all to make sure you aren't dealing with every ul on the page. By using class selectors and the built in jquery functions.

Fiddle: https://jsfiddle.net/erjfghf0/

HTML:

<a class="showHideLink">List</a>
<ul class="showHideList">
    <li>1234</li>
    <li>5678</li>
    <li>0123</li>
</ul>

JS:

$('.showHideLink').click(
    function (event) {
        $(this).next('.showHideList').toggle();
    }
);

CSS:

ul {
    display: none;
}

Since the UL has nothing to render, due to all the LI being hidden, you need to render the event action on something else. Here is my suggestion: https://jsfiddle.net/Twisty/LL948r6f/

HTML

List (<a href="#" id='toggleLink'>Toggle</a>)
<ul>
  <li>1234</li>
  <li>5678</li>
  <li>0123</li>
</ul>

CSS

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  cursor: pointer;
}

ul li {
  display: none;
}

ul li:before {
  content: "- ";
}

JQuery

$(function() {
    $('#toggleLink, ul').click(function() {
        console.log("List Items display: " + $('ul li').css('display'));
        if ($('ul li').css('display') == 'none') {
            $('ul li').show();
        } else {
            $('ul li').hide();
        }
    });
});

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