I have a ul and i want create an alert when i click on a child li.
-
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)
-
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)
-
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)