Javascript 如何禁用onclick事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13551275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to disable an onclick event?
提问by user1819709
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<table id="question">
<tr>
<td colspan="2">
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" id="mainPlusbutton" name="plusbuttonrow"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look up Previous Questions)</span>
</td>
</tr>
</table>
</form>
In the code above I am able to replace an image with another image when the if statement is met. But my problem is that when the image is replaced, it does not disable the on click event. My question is that when the image is replaced, how do I disable the onclick event onclick="return plusbutton();?
在上面的代码中,当满足 if 语句时,我可以用另一个图像替换一个图像。但我的问题是,当图像被替换时,它不会禁用点击事件。我的问题是,当图像被替换时,如何禁用 onclick 事件onclick="return plusbutton();?
回答by Ben Lee
You disable from within the plusbuttonfunction itself. First, pass the element into the function, like so:
您从plusbutton函数本身中禁用。首先,将元素传递给函数,如下所示:
<a onclick="return plusbutton(this);">
Then disable it in the function:
然后在函数中禁用它:
function plusbutton(element) {
element.onclick = '';
/* then do whatever plusbutton did before */
}
But since you are using jQuery, it's better to use handlers. So give the link an id but not an onclick, like this:
但是由于您使用的是 jQuery,因此最好使用处理程序。所以给链接一个id而不是onclick,像这样:
<a id="plusbutton" href="#">
And use jQuery.one()to bind a click handler that happens just once:
并使用jQuery.one()绑定一个只发生一次的点击处理程序:
$(document).ready(function() {
$('#plusbutton').one('click', function(ev) {
plusbutton();
return false;
});
});
回答by bashleigh
event.preventDefault();
Will prevent the element from proceeding its normal function.
将阻止元素继续其正常功能。
回答by Alessandro Minoccheri
try this code:
试试这个代码:
$('#addQuestionBtn').bind("click",function(){
$('#addQuestionBtn').unbind("click");
insertQuestion(document.form);
});
And your html:
还有你的 html:
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" />

