为什么jQuery会在添加到元素时立即触发?

时间:2012-07-12 16:14:44

标签: javascript jquery javascript-events

Here's说明问题的小提琴。我在点击一个元素到'html'元素时添加一个jQuery one绑定。我不期望在下一次单击之前触发'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);
    });
});​

1 个答案:

答案 0 :(得分:6)

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

要防止这种情况发生,请在event.stopPropgation a.target处理程序(或clickreturn falsestopPropagation)中使用preventDefault。< / p>

更新了代码(请参阅评论):Live copy

$(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);
    });
});​