停止使用jQuery运行的onclick方法

时间:2016-06-14 10:26:12

标签: javascript jquery

我有一个类似于下面的按钮

<button id="uniqueId" onclick="runMethod(this)">Submit</button>

我要做的是停止runMethod运行,直到我完成对自己的检查。我尝试过使用stopImmediatePropagation函数,但这似乎没有用。这是我的jQuery:

$j(document).on('click', '#uniqueId', function(event) {
    event.stopImmediatePropagation();
    if(condition == true) {
        // continue...
    } else {
        return false;
    }

    return false;
});

注意:runMethod基本上验证表单,然后触发提交。

4 个答案:

答案 0 :(得分:1)

你想要做什么,尤其是你想要做的事情,需要一些总是有点繁琐的解决方法。更改按钮行为的方式是一个更好的主意(例如,处理jQuery click()函数内部的整个click事件或沿着这些行的某些内容)。但是,基于您的用户首先将鼠标悬停在按钮上的假设,我找到了针对您的问题的解决方案。我相信您可以将该功能扩展到键盘的Tab事件,但它可能不适用于移动设备&#39;触摸输入。因此,请记住以下解决方案是针对您的问题的半完整解决方法:

$(document).ready(function(){
    var methodToRun = "runMethod(this)";    // Store the value of the onclick attribute of your button.
    var condition = false;                  // Suppose it is enabled at first.
    $('#uniqueId').attr('onclick',null);
    $('#uniqueId').hover(function(){
        // Check your stuff here
        condition = !condition;     // This will change to both true and false as your hover in and out of the button.
        console.log(condition);     // Log the condition's value.
        if(condition == true){      
            $('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
        }
    },
    function(){     
        console.log('inactive');    // When you stop hovering over the button, it will log this.
        $('#uniqueId').attr('onclick',null);    // Disable the on click event.
    });
});

这样做是因为它使用hover事件来触发您的检查逻辑,当用户最终点击按钮时,如果逻辑正确则启用该按钮,否则它不会执行任何操作。试试这个fiddle

P.S。:根据需要将$转换为$j以进行调整。

P.S.2:使用Javascript控制台检查小提琴是如何工作的,因为它不会自动改变页面上的任何内容。

答案 1 :(得分:0)

您的问题是submit事件,只需要:

 $('form').on('submit', function(e) {
     e.preventDefault(); 
 });

它有效。不要绑定按钮单击,只绑定提交表单。通过这种方式,您可以阻止提交表单,按钮需要是类型按钮:

 <button type="button" .....>Submit</button>

假设有单击按钮时提交的表单。

答案 2 :(得分:0)

尝试添加

event.cancelBubble();

因此您的代码变为:

$j(document).on('click', '#uniqueId', function(event) {
    // Don't propogate the event to the document


 if (event.stopPropagation) {
      event.stopPropagation();   // W3C model
  } else {
      event.cancelBubble = true; // IE model
  }



    if(condition == true) {
        // continue...
    } else {
        return false;
    }

    return false;
});

答案 3 :(得分:-1)

您的代码大部分都是正确的,但您需要删除J:

$(document).on('click', '#uniqueId', function(event) {...

您还需要从内联代码中删除onClick事件 - 当您通过jQuery分配它时,无需将其存在。

<button id="uniqueId">Submit</button>