我尝试禁用ID为#sports
的元素的点击功能。如果我在函数内调用alert()
,它可以工作,但我希望它在不调用它的情况下工作。如果我注释掉该代码,它就无法正常工作。
这是我的代码:
$("#sports").off("click").on("click", function () {
alert("disable click");
});
答案 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;
答案 1 :(得分:0)
尝试event.preventDefault()?
import X.foo
…
y.foo()
但是如果要禁用它,则不必覆盖其click函数 - 只需设置DOM元素的'disable'属性即可:
$("#sports").on("click", function (event){
event.preventDefault();
event.stopPropagation();
return false;
});