如果我在函数内部发出警报,则禁用功能正在运行

时间:2017-09-09 15:08:14

标签: javascript jquery

我尝试禁用ID为#sports的元素的点击功能。如果我在函数内调用alert(),它可以工作,但我希望它在不调用它的情况下工作。如果我注释掉该代码,它就无法正常工作。

这是我的代码:

$("#sports").off("click").on("click", function () {  
  alert("disable click");
});

2 个答案:

答案 0 :(得分:1)

您可以通过调用off()方法中的on()方法来禁用它:



$("#sports").on("click", function (){   // on button click
  console.log("click disabled");        // Do anything, console.log, alert, anything
  $(this).off("click");            // then disable the click event, set it to off,
                                   // this way the on click event won't fire 
                                   // again unless it's created, again
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sports">Click</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试event.preventDefault()?

import X.foo
…
y.foo()

但是如果要禁用它,则不必覆盖其click函数 - 只需设置DOM元素的'disable'属性即可:

$("#sports").on("click", function (event){  
   event.preventDefault();
   event.stopPropagation(); 
   return false;
});