防止onclick触发

Prevent onclick from firing

本文关键字:触发 onclick 防止      更新时间:2023-09-26

我正在处理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属性。我想运行我的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>

试试event.stopPropagation()api文档

如果condition为真,则删除'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"的按钮。添加样式显示:none。你不需要一个ready函数,只需要为按钮btn1添加style属性,或者如果这也不可能直接使用jQuery来完成post document ready。读:如何改变css显示无或块属性使用Jquery?

然后使用jQuery添加一个id为"btn2"的新按钮到表单,并添加注册btn2点击事件。在表单加载后执行

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

请参考下面的url来注册新按钮的点击事件:

为使用jQuery动态创建的按钮添加点击事件jquery -点击事件不工作的动态创建按钮

不能在一个函数中执行条件检查和clicked()逻辑吗?即

<script>
 function clicked() { 
     if(some_condition == true){
         return;
     }
     alert("clicked me");
 }
</script>