当我点击li时为什么会触发ul?
我有这个HTML:
- North America
- canada
- mexico
- united states
现在我已经编写了两个jquery函数onclick of list:
1 日 :
$(".cont-list").on("click", function(event){ alert("clicked on continent's list"); // working fine };
第二名 :
$(".contry-list").on("click", function(event){ alert("clicked on country's list"); // not working! };
在这里,当我点击cont-list时,它会被调用,但是在第二个函数中它没有被调用,而是第一个函数被调用!
是因为它是一个内在的名单? 如果是这样,那么如何处理这个问题只有在点击该列表时才会被调用?
演示就在这里
提前致谢!
那是因为事件冒出来了,你可以使用event
对象的stopPropagation
方法:
$(".contry-list").on("click", function(event){ event.stopPropagation(); alert("clicked on country's list"); });
如果要动态生成li
元素,则应委派事件:
$(document).on('click', '.coutry-list', function(){ console.log('li element is clicked'); })
$(".contry-list").on("click", function(event){ event.stopPropagation(); alert("clicked on country's list"); });
需要使用event.stopPropagation()
$(".contry-list").on("click", function(e){ e.stopPropagation(); alert("clicked on country's list"); });
在这里演示
jQuery中的修复方法是:
$(".contry-list").on("click", function(event){ alert("clicked on country's list"); // not working! return false; });
但正如epascarello指出的那样,你应该学习DOM事件冒泡(和捕获)来理解它。