[英]Prevent onclick from firing
我正在處理html中的表單提交。 請看下面的代碼
<form id="form1">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script>
$("#btn1").click(function (event) {
alert("event triggered");
if(some_condition == true){
// stop firing onclick method but it always submits the form
event.stopImmediatePropogation(); // not working
event.preventDefault(); // not working
event.stopPropogation(); // not working it's for bubbled events
}
});
function clicked(){ alert("clicked me"); }
</script>
我想停止clicked()
附加到內聯onclick
屬性的clicked()
函數。 我想運行我的jquery點擊功能,如果出現問題,我不想觸發onclick但它總是運行clicked()函數。 任何人都可以幫助我。 任何幫助是極大的贊賞。
相對於動態連接的處理程序調用onxyz
處理程序的順序因瀏覽器而異,因此您的處理程序可能無法在原始處理程序之前運行。
要處理這個問題,請保存並刪除 onclick
處理程序:
var btn = $("#btn1");
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
然后,在你的處理程序中,如果你想要調用該函數,你可以調用它:
clickhandler.call(this, event);
例:
// Get the button var btn = $("#btn1"); // Save and remove the onclick handler var clickHandler = btn[0].onclick; btn[0].onclick = false; // Hook up your handler $("#btn1").click(function(event) { alert("event triggered"); if (!confirm("Allow it?")) { // Disallowed, don't call it alert("stopped it"); } else { // Allowed, call it clickHandler.call(this, event); } }); // The onclick handler function clicked() { alert("clicked me"); }
<form id="form1" onsubmit="return false"> <button id="btn1" onclick="clicked();">Submit</button> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
如果condition為true,則刪除'onclick'屬性
if (some_condition == true) {
$("#btn1").removeAttr('onclick').click(function(event) {
alert("event triggered");
//do something
});
}
function clicked() {
alert("clicked me");
}
我正在分享快速的解決方法而不知道為什么你不能添加邏輯來停止添加“onclick =”clicked();“你說的代碼會自動添加。
我建議你隱藏id為“btn1”的按鈕。 添加樣式顯示:無。 你不需要為此准備好功能,但只需將樣式屬性添加到按鈕btn1,或者如果這也不可能直接添加,那么使用jQuery來准備該文檔。 閱讀: 如何使用Jquery更改css display none或block屬性?
然后使用id為“btn2”的jQuery向表單添加一個新按鈕,並添加注冊btn2 click事件。 表格加載后執行此操作。
<form id="form1">
<div id="newbut">
<button id="btn1" onclick="clicked();">Submit</button>
</div>
</form>
jQuery("#newbut").html('<button id="btn2">Submit</button>');
$(document).on('click', '#btn2', function(){
// Your Code
});
請參閱以下網址,了解如何為新按鈕注冊點擊事件:
嘗試event.stopPropagation()
api docs
你不能在一個函數中進行條件檢查和clicked()邏輯嗎? 即
<script>
function clicked() {
if(some_condition == true){
return;
}
alert("clicked me");
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.