我的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"
我希望创建一些函数或另一种方式来优化代码。
答案 0 :(得分:0)
给所有元素一个类
例如
<button id="boxed" class="ClassName"></button>
<button id="flow" class="ClassName"></button>
然后使用:
var elements = document.getElementsByClassName("ClassName");
for (var i = 0; i < elements.length; i++) {
elements[i].onclick = function() {
window.location.href = "../3infoCardPremium/3infoCardPremium.html"
}
};