我想在纯Javascript中实现以下
单击按钮时,会调用一个函数
<button id= "myButton", onclick="onlyOnce()">Hit me</button>
onlyOnce
设置一些变量并调用另一个函数。然后onlyOnce
将自己与按钮分离,另一个函数将自己添加到按钮上,所以现在每次点击都会调用它
我无法使其发挥作用
这是代码
<button id= "myButton", onclick="onlyOnce()">Hit me</button>
function onlyOnce() {
console.log("onlyOnce called!");
//do some code...
otherFunction();
document.getElementById("myButton").addEventListener("click", otherFunction, false);
document.getElementById("myButton").removeEventListener("click", onlyOnce, false);
}
function otherFunction() {
console.log("otherFunction called!");
}
当我第一次点击按钮时,我看到onlyOnce called!
和otherFunction called!
,所以这是正确的。
当我继续按下按钮时,我仍然会看到onlyOnce called!
和otherFunction called!
,所以这是错误的,因为onlyOnce
没有分离自己。我该如何解决?
由于
答案 0 :(得分:4)
这样做的一种方式是:
function onlyOnce() {
console.log("onlyOnce called!");
//do some code...
otherFunction();
document.getElementById("myButton").onclick = otherFunction; // assign the other function to the onclick property of the element.
}
答案 1 :(得分:2)
这是更好的解决方案(不覆盖对其他功能的引用):
function onlyOnce() {
console.log("onlyOnce called!");
//do some code...
otherFunction();
document.getElementById("myButton").addEventListener("click", otherFunction, false);
document.getElementById("myButton").removeEventListener("click", onlyOnce, false);
}
function otherFunction() {
console.log("otherFunction called!");
}
document.getElementById('myButton').addEventListener('click', onlyOnce);
和HTML:
<button id= "myButton">Hit me</button>
答案 2 :(得分:0)
您可以使用一个函数来执行此操作,该函数将所有调用委托给在创建事件处理程序时配置的其他函数
function once(first,others){
var isFirstTime = true;
return function(e){
if(isFirstTime){
first(e);
isFirstTime = false;
}
else{
others(e)
}
}
}
下面是一个例子
function once(first,others){
var isFirstTime = true;
return function(e){
if(isFirstTime){
first(e);
isFirstTime = false;
}
else{
others(e)
}
}
}
function onceOnly(){
console.log("once only");
}
function everyOtherTime(){
console.log("other times");
}
document.getElementById("click").addEventListener("click",once(onceOnly,everyOtherTime))
<button id="click">Click me</button>
答案 3 :(得分:0)
<button id= "myButton", onclick="onlyOnce()">Hit me</button>
<script type="text/javascript">
var onlyOnce = function() {
onlyOnce = function(){}; //As soon as it runs, it will be set to an empty object and will not run again
console.log("onlyOnce called!");
//do some code...
otherFunction();
document.getElementById("myButton").addEventListener("click", otherFunction, false);
document.getElementById("myButton").removeEventListener("click", onlyOnce, false);
}
function otherFunction() {
console.log("otherFunction called!");
}
</script>
/* alternative
var onlyOnce = function() {
console.log("onlyOnce called!");
onlyOnce = otherFunction;
//do some code...
otherFunction();
}
*/
</body>
祝福!