在 Javascript 事件 DOM 中禁用功能
Disable Function in Javascript event DOM
我对 javascript 有疑问,
在我的 html 代码中:
<input onclick="myFunction();" />
<script>
function myFunction(){
//excecution of this fucntion
}
</script>
点击输入后,函数运行s。但我希望 myFunction 在第一次点击后被禁用,所以当我再次点击时,myFunction 不会 运行.
只需删除属性
<input onclick="myFunction(this);" />
<script>
function myFunction(elem){
// code here
elem.removeAttribute('onclick')
}
</script>
或者更好地使用事件侦听器
<input id="myInput" />
<script>
document.getElementById('myInput').addEventListener('click', myFunction, false);
function myFunction(elem){
// code here
this.removeEventListener('click', myFunction);
}
</script>
一种方法是在代码执行后将其设置为空函数。
function myFunction(){
//(..) Some code
myfunction = function(){}; // empty the function so nothing happens next time
}
如果您使用 jQuery(因为您已将其包含在标签中),我会选择 .one()
:
<input type="txt" class="my-input" />
function activateClick(){
// single click:
$('.my-input').one('click', function(){
// do stuff ...
});
}
// Activate single click on input element
// Can be reactivated later on, using the same function (see DEMO):
activateClick();
使用布尔指示符来确定函数是否已经 运行。这种方法的优点是以后很容易重置功能状态。
<!DOCTYPE html>
<html>
<body>
<button onclick='func();'>Function</button>
</body>
<script>
var funcActive=true;
function func() {
if (funcActive) {
funcActive=false;
alert('func ran');
}
}
</script>
</html>
我对 javascript 有疑问, 在我的 html 代码中:
<input onclick="myFunction();" />
<script>
function myFunction(){
//excecution of this fucntion
}
</script>
点击输入后,函数运行s。但我希望 myFunction 在第一次点击后被禁用,所以当我再次点击时,myFunction 不会 运行.
只需删除属性
<input onclick="myFunction(this);" />
<script>
function myFunction(elem){
// code here
elem.removeAttribute('onclick')
}
</script>
或者更好地使用事件侦听器
<input id="myInput" />
<script>
document.getElementById('myInput').addEventListener('click', myFunction, false);
function myFunction(elem){
// code here
this.removeEventListener('click', myFunction);
}
</script>
一种方法是在代码执行后将其设置为空函数。
function myFunction(){
//(..) Some code
myfunction = function(){}; // empty the function so nothing happens next time
}
如果您使用 jQuery(因为您已将其包含在标签中),我会选择 .one()
:
<input type="txt" class="my-input" />
function activateClick(){
// single click:
$('.my-input').one('click', function(){
// do stuff ...
});
}
// Activate single click on input element
// Can be reactivated later on, using the same function (see DEMO):
activateClick();
使用布尔指示符来确定函数是否已经 运行。这种方法的优点是以后很容易重置功能状态。
<!DOCTYPE html>
<html>
<body>
<button onclick='func();'>Function</button>
</body>
<script>
var funcActive=true;
function func() {
if (funcActive) {
funcActive=false;
alert('func ran');
}
}
</script>
</html>