问题描述
有没有办法只让listitem
的内部元素做点什么?
Is there is a way to only let the inner element of a listitem
do something?
我有一个列表元素,其中可以包含具有特定类的a
标签.
I have list elements that can contain a
tags with a certain class.
内部a
标记绑定到实时单击事件处理程序.列表项本身还具有click事件处理程序.
The inner a
tags are bound to a live click event handler. The list items themselves have also a click event handler.
类似这样的东西
<li>some text<a class="someClassName">some text</a></li>
使用a
标记的处理程序
$('#somelist li a').live("click", function(e)
这就是添加li项目的事件的方式
and this is how the event for li item is added
$(markers).each(function(i,marker){
$("<li />")
.html("Locatie "+'<a class="ol id"><strong>'+ids[i]+'</strong></a>')
.click(function(e){
showLocation(marker, i);
})
.appendTo("#somelist ");
推荐答案
jQuery中的live
方法通过事件委托工作,这是将所有冒泡事件从单个元素捕获到一个共同祖先的行为(在您的情况下)其document
).
The live
method in jQuery works via event delegation, which is the act of catching all the bubbled events from individual elements onto a common ancestor (in your case its document
).
停止click事件的传播/冒泡发生在处理程序元素(这是共同的祖先,而不是元素本身)上,并且位于您要避免的li
上方.
Stopping the propagation/bubbling of the click event occurs on the handler element (which is the common ancestor, not on the element itself) and exists way above the li
that you are trying to avoid.
因此,在调用stopPropagation
方法时,我们已经遍历了dom并传递了li
元素.
So by the time the stopPropagation
method gets called, we've already traversed down the dom and passed the li
element.
本质上是在十字路口后的 处放一个停车标志.
It's essentially putting a stop sign 200ft after the intersection.
因此,您将需要使用bind
和stopPropagation
或找到其他解决方案.
So you'll either need to use bind
and stopPropagation
or find a different solution.
以下是我所讨论的示例: http://jsbin.com/ibuxo (检查控制台)
Here is an example of what I'm talking about: http://jsbin.com/ibuxo (check the console)
您可以在 http://jsbin.com/ibuxo/edit
对于此问题,我建议的解决方案是使用bind
而不是live
.
My suggested solution to this problem would be to use bind
instead of live
.
这需要您做一些额外的工作,但这还不错.
This requires you to do a little bit extra work, but it's not so bad.
您可能正在使用live
,因为您要添加新元素,并且希望它们具有相同的功能.当您将它们输入到页面时,应通过绑定它们来做到这一点.这是一个例子
You are probably using live
because you are adding new elements, and you want them to have the same functionality. You should do this by binding them when you input them to the page. Here's an example
$(function(){
var myAnchorHandler = function(e){
alert('clicked!');
e.stopPropagation();
return false;
};
// initial bind
$('#somelist li a').click(myAnchorHandler);
// code where you input more li elements to the list with links
$('#somelist').append(
// bind your function to the element now, and then append it
$('<li><a>hi</a></li>').find('a').click(myAnchorHandler).parent()
);
});
这篇关于jQuery如何仅在内部元素上执行事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!