Reputation: 3
I am trying to trigger a click event on every item in a nested list and return the text of the clicked item. The return text part works fine but when I click outside the list, it still triggers the click event and returns the text of the list item in the corresponding line. Has anyone faced such an issue?
HTML:
<div id="myDiv">
<ul id = "u" class="nam">
<li id="i1" class="nam">John</li>
<li id="i2" class="nam">
<ul id="uu">
<li id="i3">F</li>
<li id="i4">Fitzgerald</li>
</ul>
</li>
<li id="i5" class="nam">Kennedy</li>
</ul>
</div>
jQuery Code:
$("#u").on("click","li",function(event){
event.stopPropagation();
alert($(this).text());
});
Upvotes: 0
Views: 66
Reputation: 3065
Giving fixed width will solve that but another solution is wrapping li
content with span
. You can do this with jquery if you dont wanna do it in your html code then build your click event for li span
selector.
$("li").not(":has(ul li)").wrapInner("<span></span>");
$("#u").on("click","li span",function(event){
event.stopPropagation();
alert($(this).text());
});
Upvotes: 1
Reputation: 656
Just style your div ul li and your problem will be solved because the element you are using they are the block element which using the full page, so style your page or provide some fixed pixel it will work.
Upvotes: 0