问题
I have this html:
<ul class='loc-list'>
<li id="where_7" class="cont-list">North America
<ul>
<li id="contry_114" class="contry-list">canada</li>
<li id="contry_115" class="contry-list">mexico</li>
<li id="contry_117" class="contry-list">united states</li>
</ul>
</li>
</ul>
Now I have written two jquery functions onclick of list as:
1st:
$(".cont-list").on("click", function(event){
alert("clicked on continent's list"); // working fine
};
2nd:
$(".contry-list").on("click", function(event){
alert("clicked on country's list"); // not working!
};
Here when I click on cont-list it get called ones as it should , but in the 2nd function it is not getting called instead it 1st function get called!
Is is because of it being an inner list? If so, then how to deal with this so that it will be called only when clicked on that list only?
The demo is here
Thanks in advance!
回答1:
That's because events bubble up, you can use stopPropagation
method of the event
object:
$(".contry-list").on("click", function(event){
event.stopPropagation();
alert("clicked on country's list");
});
If you are generating the li
elements dynamically you should delegate the event:
$(document).on('click', '.coutry-list', function(){
console.log('li element is clicked');
})
回答2:
$(".contry-list").on("click", function(event){
event.stopPropagation();
alert("clicked on country's list");
});
回答3:
Need to use event.stopPropagation()
$(".contry-list").on("click", function(e){
e.stopPropagation();
alert("clicked on country's list");
});
Demo Here
回答4:
A fix in jQuery would be:
$(".contry-list").on("click", function(event){
alert("clicked on country's list"); // not working!
return false;
});
But as epascarello points out, you should learn about DOM event bubbling (and capturing) to understand it.
来源:https://stackoverflow.com/questions/15137332/why-ul-gets-triggered-when-i-click-on-li