防止onclick被解雇

时间:2016-07-02 08:01:30

标签: javascript jquery

我正在处理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()函数。任何人都可以帮助我。任何帮助是极大的赞赏。

5 个答案:

答案 0 :(得分:5)

相对于动态附加处理程序调用{​​{1}}处理程序的顺序因浏览器而异,因此您的处理程序可能无法在原始处理程序之前运行。

要解决这个问题,请保存并删除 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");
}

答案 1 :(得分:0)

如果条件为真则删除'onclick'属性

if (some_condition == true) {
    $("#btn1").removeAttr('onclick').click(function(event) {
        alert("event triggered");

        //do something
    });
}


function clicked() {
    alert("clicked me");
}

答案 2 :(得分:0)

我正在分享快速的解决方法而不知道为什么你不能添加逻辑来停止添加“onclick =”clicked();“你说的代码会自动添加。

我建议您隐藏ID为“btn1”的按钮。添加样式显示:无。你不需要为此准备好功能,但只需将样式属性添加到按钮btn1,或者如果这也不可能直接,那么使用jQuery来准备该文档。 阅读: How to change css display none or block property using Jquery?

然后使用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
 });

请参阅以下网址,了解如何为新按钮注册点击事件:

Adding click event for a button created dynamically using jQuery jquery - Click event not working for dynamically created button

答案 3 :(得分:-1)

试试event.stopPropagation() api docs

答案 4 :(得分:-1)

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

 #include <spdlog.h>
相关问题