Javascript 优化多个window.location.href=";index.html“;

Javascript 优化多个window.location.href=";index.html“;,javascript,Javascript,我的HTML中有多个ID。当我单击该元素(.onclick)时,我想将它们全部(window.location.href)重定向到同一个站点 到目前为止,我已尝试过此代码,但不起作用: document.getElementById("boxed", "inmerse", "flow", "scape", "fierce", "name6", "name7", "name8", "name9").onclick = () => window.location.href = "../3inf

我的HTML中有多个ID。当我单击该元素(.onclick)时,我想将它们全部(window.location.href)重定向到同一个站点

到目前为止,我已尝试过此代码,但不起作用:

document.getElementById("boxed", "inmerse", "flow", "scape", "fierce", "name6", "name7", "name8", "name9").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"
这就是有效的代码

document.getElementById("boxed").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"

document.getElementById("immerse").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"


document.getElementById("flow").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"


document.getElementById("scape").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"


document.getElementById("fierce").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"


document.getElementById("name6").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"


document.getElementById("name7").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"


document.getElementById("name8").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"


document.getElementById("name9").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html"

我希望创建一些函数或其他方法来优化代码。

给所有元素一个类

e、 g


然后使用:

var elements = document.getElementsByClassName("ClassName");

for (var i = 0; i < elements.length; i++) {
    elements[i].onclick = function() {
        window.location.href = "../3infoCardPremium/3infoCardPremium.html"
    }
};
var elements=document.getElementsByClassName(“ClassName”);
对于(var i=0;i
for在数组上循环并绑定事件为什么不让相关的DOM节点锚定标记?为什么您需要Javascript?也许您应该阅读HTML classesIndeed,
GetElementsByCassName(“ClassName”)
返回一个
数组
谢谢,@Xander code正在工作,对每个人来说都更好=)
var elements = document.getElementsByClassName("ClassName");

for (var i = 0; i < elements.length; i++) {
    elements[i].onclick = function() {
        window.location.href = "../3infoCardPremium/3infoCardPremium.html"
    }
};