简体   繁体   English

如何在委托()中使用event.stopPropagation()

[英]How to use event.stopPropagation() in delegate()

My Code is like following in html: 我的代码类似于html中的以下代码:

<li class="arrow">    
    <div>
        <a href="javascript:void(0);" class="anchor">remove</a> 
    </div>                      
</li>

And I bind my elements using deligate() jquery method (because elements appear dynamically) 我使用deligate()jQuery方法绑定元素(因为元素动态显示)

$obj.delegate(".arrow", "click", function() {
    alert("clicked on arrow");
});

$obj.delegate(".anchor", "click", function(event) {
     event.stopPropagation();
     alert("anchor clicked");
});

My Problem is, when I click on ".anchor" then both events occurs. 我的问题是,当我单击“ .anchor”时,两个事件都会发生。 can anyone tell me how to use event.stopPropagation() in this context? 谁能告诉我在这种情况下如何使用event.stopPropagation()? I tried like the above but not working. 我尝试了上述方法,但无法正常工作。 Is there any other way to do this? 还有其他方法吗?

EDIT: I tried with calling event.isPropagationStopped(), and it returns true. 编辑:我尝试调用event.isPropagationStopped(),它返回true。 but still both events called. 但是两个事件仍然被调用。

There is limitations when delegate or live is used and stopPropagation . 当有限制delegatelive使用和stopPropagation

You return false in you handler to prevent both eventPropagation and default 您在处理程序中返回false以防止eventPropagationdefault

Try 尝试

$obj.delegate(".anchor", "click", function(event) {
     alert("anchor clicked");
     return false;
});

My understanding is that with .delegate and .live you need to return false . 我的理解是,使用.delegate.live您需要return false I believe this is because of how the event is attached - not to the element but to it's ancestor. 我相信这是因为事件的附加方式-不是元素,而是元素的祖先。

Here is an example: http://jsfiddle.net/G3k8Z/ 这是一个示例: http : //jsfiddle.net/G3k8Z/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM