JS同一个元素点击实现不同的事件应该怎么写
我对一个元素创建了点击事件 如下代码partBtn1.addEventListener("click",fn)
function fn(){
window.location.href = "./020index.html";
}
function fn1(){
window.location.href = "./030index.html";
}
第一点击我想让页面去往"./020index.html";再次点击去往"./030index.html";
因该如何书写 可以使用一个变量来记录点击事件的次数,根据点击次数的不同执行不同的动作。代码如下:
var clickCount = 0;// 初始化点击次数为0
partBtn1.addEventListener("click", function() {
if (clickCount % 2 === 0) {
window.location.href = "./020index.html";// 第一次点击,跳转到"./020index.html"
} else {
window.location.href = "./030index.html";// 再次点击,跳转到"./030index.html"
}
clickCount++;// 每次点击后点击次数增加1
});
这样,当你第一次点击 "partBtn1" 元素时,页面将会跳转到 "./020index.html";再次点击时,页面会跳转到 "./030index.html";以此类推。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页:
[1]