本文介绍了jQuery on():奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码可在我的网站上使用:

This code works on my site:

$(function(){
    $('.link-follow-stop').on('click', function(event){
        console.log('|||');
        return false;
    });
});

但这不是:

$(function(){
    $(document).on('click', '.link-follow-stop', function(event){
        console.log('|||');

        return false;
    });
});

在我的网站上运行第二个代码示例时,我没有看到任何错误,但是当我单击.link-follow-stop链接时,不会触发console.log调用.

I see no errors when running the second code sample on my site, but the console.log call does not fire when I click the .link-follow-stop link.

我尝试在jsFiddle上运行第二个代码示例,它的工作与预期的一样.有什么问题吗?

I tried running the second code sample at jsFiddle and it worked like I was expected. What can be wrong?

与"link-follow-stop"类的链接是静态的(我的意思是不是动态的).

Link with class 'link-follow-stop' is static (I mean not dynamic).

推荐答案

如果对包含.link-follow-stop且使用e.stopPropagation()的元素具有单击处理程序,则将阻止事件起泡到document . .on()的第二种形式取决于事件冒泡直到该处理程序绑定到的元素.然后检查事件的实际目标是否与选择器匹配.

If you have a click handler on an element that contains .link-follow-stop and it uses e.stopPropagation(), this will prevent the event from bubbling up to document. The second form of .on() depends on the event bubbling up to the element that that handler is bound to; it then checks whether the actual target of the event matches the selector.

以下内容证明了这一点:

The following demonstrates this:

<div class="outer">
    <div class="inner">
        Click here
    </div>
</div>

$(function() {
    $(document).on("click", ".inner", function() {
        alert("inner");
    });
    $(".outer").click(function(e) {
        e.stopPropagation();
        alert("outer");
    });
});

FIDDLE

使用.on()进行委派时,应将处理程序绑定到包含动态元素的最特定的静态元素.这样可以最大程度地减少其他处理程序进行干预并防止冒泡的风险.

When you delegate with .on() you should bind the handler to the most specific static element(s) that contains the dynamic element. This minimizes the risk that another handler will interfere and prevent bubbling.

这篇关于jQuery on():奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 14:27