1

想象一下这样的事情。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Testing event bubbling</title>
    <script src="js/jquery/jquery-2.0.0.js"></script>
    <script>
        $(document).on('click', 'div', function(e) {
            e.preventDefault();
            console.log('Clicked');
            return true;
        });
        $(document).on('submit', 'form', function(e) {
            e.preventDefault();
            console.log('Submitted');
        });

    </script>
</head>
<body>
<form>
    <div><div><div>
        Click this.
        <input type="submit">
    </div></div></div>
</form>

</body>
</html>

现在,当您单击提交按钮时,单击事件被捕获并向下传播到所有 DIV,您会看到“单击”三次。我的特殊之处在于,这似乎跳过了表单提交事件。如果我删除 Click 绑定,则提交事件会正确触发。有没有在表单上手动触发 submit() 的方法?我知道我可以使点击事件更具体,因此它不适用于提交按钮,但是......我有一个奇怪的用例。

我在这里做错了什么?如果触发了一个事件,是否意味着所有其他优先级较低的事件都将被忽略?

4

3 回答 3

1

e.preventDefault() is used to prevent the default action of some controls. For example, if you click a link, it will try to load its href, if you click a submit button, it will try to submit the form. So, preventDefault is used to prevent those actions.

If you don't want the submit to "interrupt", in other words, if you want to submit the form, remove the preventDefault from your click event.

Now, second point, the click event is propagated 3 times. You have something like:

<div>
    Div 1
    <div>
        Div 2
    </div>
</div>

And you are binding the onclick method to every <div> on the page. So, 3 divs, 3 onclicks. If all divs are overlapped then when you click the inner one, you are clicking it's parent div too, and so on. You can use stopPropagation() if you don't want the event to propagate to deeper divs (think of it as "layers" one over each other).

于 2013-04-26T10:33:03.287 回答
1

您可以使用event.stopPropagation()来阻止事件冒泡到其他元素。无需e.preventDefault()单击此处调用 - 它会停止执行默认操作,这不是您所追求的。

于 2013-04-26T10:22:23.953 回答
0

您可以检查单击是否发生在输入字段中

$(document).on('click', 'div', function(e) {
    if(!$(e.target).is('input')){
        e.preventDefault();
    }  
    console.log('Clicked');
    return true;
});
$(document).on('submit', 'form', function(e) {
    e.preventDefault();
    console.log('Submitted');
});
于 2013-04-26T10:23:36.807 回答