只是那个人 发表于 2024-3-11 08:41:09

JS同一个元素点击实现不同的事件应该怎么写

我对一个元素创建了点击事件 如下代码

partBtn1.addEventListener("click",fn)
    function fn(){
      window.location.href = "./020index.html";
    }
    function fn1(){
      window.location.href = "./030index.html";
    }

第一点击我想让页面去往"./020index.html";再次点击去往"./030index.html";

因该如何书写

FishC 发表于 2024-3-11 08:41:18

可以使用一个变量来记录点击事件的次数,根据点击次数的不同执行不同的动作。代码如下:

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]
查看完整版本: JS同一个元素点击实现不同的事件应该怎么写