所以我有1个按钮和3个功能。我希望在按下按钮时运行一个功能,但是在此之后,下次单击它时,它将运行另一个功能,依此类推。我该怎么做呢?我尝试做
currentfunc = func1
element.onclick = currentfunc
function func1(){
//Something
currentfunc = func2
}
function func2(){
//Something
currentfunc = func3
}
function func3(){
//Something
}
它在第一次单击时有效,但是此后它将停止运行功能
答案 0 :(得分:1)
您可以通过实现保存当前状态的变量来实现这一目标:
var state = 1;
function func1(){...}
function func2(){...}
function func3(){...}
element.onclick = function() {
switch (state) {
case 1:
state = 2;
return func1.apply(this, arguments);
case 2:
state = 3;
return func2.apply(this, arguments);
case 3:
state = 1; // go back to call func1 next time
return func3.apply(this, arguments);
}
}
请参阅:
答案 1 :(得分:1)
可以请您尝试一下。我已经完成了Jquery。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<a id="aclick" onclick="func1()">click me</a>
<script>
function func1(){
alert("func1")
$("#aclick").attr("onclick","func2()")
}
function func2(){
alert("func2")
$("#aclick").attr("onclick","func3()")
}
function func3(){
alert("func3")
$("#aclick").attr("onclick","func1()")
}
</script>
</body>
</html>
这里是javascript
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a id="aclick" onclick="func1()">click me</a>
<script>
function func1(){
debugger
alert("func1")
var a = document .getElementById("aclick");
a.setAttribute("onclick", "func2()");
}
function func2(){
alert("func2")
var a = document .getElementById("aclick");
a.setAttribute("onclick", "func3()");
}
function func3(){
alert("func3")
var a = document .getElementById("aclick");
a.setAttribute("onclick", "func1()");
}
</script>
</body>
</html>
答案 2 :(得分:0)
您可以将函数添加到数组中,实现一个计数器,然后在单击按钮时调用与计数器代表的索引相对应的函数。
const fns = [
function func1() {
console.log(1);
},
function func2() {
console.log(2);
},
function func3() {
console.log(3);
}
];
// Grab the button, and add a listener to it
// The listener calls `createClickFn` with the array -
// the function returns a new function which is assigned to
// the listener
const button = document.querySelector('button');
button.addEventListener('click', createClickFn(fns), false);
// A closure that sets a counter, and returns a function
// that calls the function in the array the index of which
// corresponds to the counter
// When the counter is the same as the length of the array
// set it back to zero
function createClickFn(fns) {
let count = 0;
return function () {
fns[count]();
count = (count === fns.length - 1) ? 0 : count + 1;
}
}
<button>Click!</button>
答案 3 :(得分:0)
一个更好的实现是使用generator,请注意IE浏览器不支持它:
function* gen() {
yield function () { console.log('call 1')};
yield function () { console.log('call 2')};
yield function () { console.log('call 3')};
}
let g = gen();
document.getElementById('generator').addEventListener('click', function(e) {
let callback = g.next();
if(callback.done) {
g = gen();
callback = g.next();
}
callback.value();
})
<button id="generator">click me</button>