2014-01-30 49 views
0

說我有一個輸入如何防止父的onclick被調用

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

在我看來,父母的行爲仍在運行。

+0

想到的是要仔細檢查'validationFail'返回你所期望的第一件事。您可能還需要'返回false'來阻止鏈接導航,和/或刪除可能已分配的其他處理程序。 – brichins

+1

難道你不能只在你的jQuery腳本的點擊處理程序中調用actionTaken,而不是根本沒有內聯事件? –

+0

actionTaken是由JSF(javaserver faces)生成的一些隨機代碼 –

回答

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

出現這種情況的原因是,無論是內聯onclick和jQuery click事件處理程序在點擊鏈接的同時觸發。您可以考慮嵌套click事件處理程序中的actionTaken功能,像這樣:

function actionTaken(){ 
    ... 
} 

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

我希望這有助於!

+0

不能做到這一點。 actionTaken從JSF框架生成 –

0

其實我的答案是一定的相關性安德烈

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); 
}