如何防止调用父onclick

时间:2014-01-30 17:31:09

标签: jquery events preventdefault stoppropagation

说我有输入

<a href="/somepage.html" id="somePage" onclick="actionTaken();"/>

现在我已经附加了额外的jquery事件处理程序。

$("#somePage").click(function(event) {
    // this needs to be executed before the default "actionTaken();" event. 
    if (validationFail()) {
         // prevent the onclick event and link from going through.
         event.preventDefault();
         event.stopPropagation();
    }
});

在我看来,父母行动仍在继续。

3 个答案:

答案 0 :(得分:0)

您可能需要运行unbind()来删除以前分配的处理程序(它们不是父项,它们只是其他处理程序):

$("#somePage").unbind("click");
$("#somePage").click(function(event) {
    // this needs to be executed before the default "actionTaken();" event. 
    if (validationFail()) {
         // prevent the onclick event and link from going through.
         event.preventDefault();
         event.stopPropagation();
    }
});

答案 1 :(得分:0)

发生这种情况的原因是内联onclick和jQuery click事件处理程序在单击链接的同时触发。您可以考虑在actionTaken事件处理程序中嵌套click函数,如下所示:

function actionTaken(){
    ...
}

$('#somePage').click(function(e){
    if (validationFail() !== true){
        actionTaken();
    }
});

我希望这有帮助!

答案 2 :(得分:0)

实际上我的答案与Andrei有些相关

var somePage, handler;
somePage = $("#somePage");
if (somePage.length) {
    handler = somePage.prop("onclick");
    somePage.removeProp("onclick");
    somePage.click(function(event) {
        // this needs to be executed before the default "actionTaken();" event. 
         if (validationFail()) {
             // prevent the onclick event and link from going through.
             event.preventDefault();
             event.stopPropagation();
         }
    });
    somePage.click(handler);   
}