当我点击li时为什么会触发ul? [英] Why ul gets triggered when I click on li?

查看:250
本文介绍了当我点击li时为什么会触发ul?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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>

现在我已经编写了两个jquery函数onclick of list:

Now I have written two jquery functions onclick of list as:

1 st

1st:

$(".cont-list").on("click", function(event){
     alert("clicked on continent's list"); // working fine
 };

2 nd

2nd:

$(".contry-list").on("click", function(event){
     alert("clicked on country's list");  // not working!
 };

当我点击续约列表它应该被调用,但在 2 nd 函数中,被调用而不是 1 st 函数被调用!

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?

演示在这里

提前致谢!

推荐答案

那是因为事件冒出来了,你可以使用事件的 stopPropagation 方法对象:

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");  
});

如果要动态生成 li 元素您应该委派活动:

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');
})

这篇关于当我点击li时为什么会触发ul?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆