jQuery [removed]() child selector

前端 未结 3 913
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 18:05

I have a ul and i want create an alert when i click on a child li.

    相关标签:
    3条回答
    • 2021-01-28 18:45

      You can use simply css child selector as below mentioned. It will apply direct children not just any descendant.

      Note: As per http://w3.org standards you can't make the div direct children of ul. The div tag should come inside the li's.

      jQuery("#myul > li").click(function(){
      
          alert('hey!');
      
      });
      
      0 讨论(0)
    • 2021-01-28 18:47

      You can use

      $(document).on('click','#myul li', eventHandler) 
      

      which means you're registering an event handler on the document but eventHandler will be invoked only when the event originated from #myul li i.e for any li child of myul, not just the immediate child, can be a descendant as well which fits your case.

      But I suggest that you even reduce the scope of the event registration to the closest ancestor of li like below.

      $('#myul').on('click','li', eventHandler)
      
      0 讨论(0)
    • 2021-01-28 19:06

      ul elements can only contain li elements eventually mixed with ol and ul elements. You can can fix your html and jquery to be like:

      $(document).on('click', '#myul ul li', function() {
        alert('hey!');
      });
      ul,
      li {
        list-style-type: none;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <ul id="myul">
        <li class="test">
          <ul class="test1">
            <li>rasd</li>
            <li>sadsad</li>
          </ul>
        </li>
      </ul>

      0 讨论(0)
    提交回复
热议问题