为什么jQuery'it’当它着火的时候;s添加到元素中

Why does jQuery's one fire immediately when it's added to an element?

本文关键字:添加 元素 jQuery it 为什么      更新时间:2023-09-26

这里有一个小提琴来说明这个问题。我正在添加一个jQuery-one绑定,只需单击一个元素到"html"元素即可。我不希望"one"事件处理程序在下一次单击之前激发,但它在添加绑定的单击时激发。如果它是一个添加了"one"事件处理程序的更具体的元素,这似乎不是问题,但当我使用"html"或"body"作为元素时,就会发生这种情况,这正是我想要做的

这对我来说没有意义,我认为第一次点击会为下一次点击添加一个,而且点击链接时不会触发。

顺便说一句,我的实际问题可能会以更好的方式解决,但我遇到了这个问题,很好奇为什么它没有像我预期的那样起作用。


代码:

html:

<div id='hello'>hello</div>
<a class="title" href="#">this example</a> is a test​

js:

$(function() {
    $('a.title').click(function() {
        var htmlClickBind = function (e) {
            console.log('clicked on html, e.target = ' + e.target);
            console.log(e.target == '');
            if (!$(e.target).is('a') ) {
                console.log('cleared click event');
            }
            else {
                $('html').one('click', htmlClickBind);
            }
        };
        $('html').one('click', htmlClickBind);
    });
});​

a.target元素上的click事件冒泡到html元素,您(刚刚添加的)处理程序会在那里看到它。

要防止这种情况,请在a.target click处理程序中使用event.stopPropgation(或执行stopPropagationpreventDefaultreturn false)。

更新代码(见评论):实时复制

$(function() {
    // Accept the event arg ----v
    $('a.title').click(function(e) {
        // Stop propagation
        e.stopPropagation();
        var htmlClickBind = function (e) {
            console.log('clicked on html, e.target = ' + e.target);
            console.log(e.target == '');
            if (!$(e.target).is('a') ) {
                console.log('cleared click event');
            }
            else {
                $('html').one('click', htmlClickBind);
            }
        };
        $('html').one('click', htmlClickBind);
    });
});​