除非调试,否则jQuery event.preventDefault()不起作用

时间:2015-06-17 20:51:02

标签: javascript jquery events javascript-events event-handling

我正在尝试使用this方法将GET参数转换为POST。即使单击鼠标中键,我也希望正确处理锚点。

这就是我对事件处理程序绑定的方式:

$(document).ready(function () {
    $(".post").each(function(){
        $(this).mousedown(function(evt){
            switch(evt.which){
                case 1:
                case 2:
                    evt.stopPropagation();
                    evt.preventDefault();
                    get2post(evt);
                    break;
            }
        });
    });
});

当我点击.post锚点时,浏览器发送POST请求,然后立即中止它,发送所谓的被阻止的GET请求。

Firebug reports that the POST request was aborted, and then the GET is sent

(请不要介意处理GET请求时发生的错误。这恰好是因为参数应该通过POST发送,而不是GET)

最后,当我调试get2post函数时,它按预期工作。我对evt.preventDefault()行仅在调试时的工作原理没有任何线索。

我在Firefox和Chrome上尝试过,并得到了相同的结果。这里发生了什么?除非调试,为什么evt.preventDefault()不起作用?

1 个答案:

答案 0 :(得分:1)

anchor事件中,buttoninputmousedown没有默认行为。您希望改为阻止click事件的默认行为。

$(function () {
    $('.post').on('click', function (evt) {
        switch (evt.which) {
            case 1:
            case 2:
                evt.stopPropagation();
                evt.preventDefault();
                get2post(evt);
                break;
        }
    });
});
相关问题