gpt4 book ai didi

javascript - 如何减少此代码中的变量和 if 语句的数量?

转载 作者:行者123 更新时间:2023-11-30 09:21:44 25 4
gpt4 key购买 nike

减少代码使用量的最佳方法是什么?最终我将有大约 20 个按钮,因此似乎没有必要多次编写变量和 if 语句。有人可以建议一种减少、更清晰的代码的方法吗?将变量放入数组中是否有帮助?

var art1 = document.getElementById("article1").textContent;
var button1 = document.getElementById("btn1");

var art2 = document.getElementById("article2").textContent;
var button2 = document.getElementById("btn2");

var art3 = document.getElementById("article3").textContent;
var button3 = document.getElementById("btn3");



if (true) {
button1.addEventListener("click", function() {
document.getElementById("fillMe").innerHTML = art1;
});
}

if (true) {
button2.addEventListener("click", function() {
document.getElementById("fillMe").innerHTML = art2;
});
}

if (true) {
button3.addEventListener("click", function() {
document.getElementById("fillMe").innerHTML = art3;
});
}
.article {
display: none;
}
<div id="article1" class="article">
Article 1
</div>


<div id="article2" class="article">
Article 2
</div>


<div id="article3" class="article">
Article 3
</div>




<button class ="button" id="btn1">Button 1</button>
<button class ="button" id="btn2">Button 2</button>
<button class ="button" id="btn3">Button 3</button>

<div id="fillMe"></div>

最佳答案

["1", "2", "3"].forEach(function(i) {
if (true) { // I do not know why you need this though
var content = document.getElementById("article" + i).textContent;
var oButton = document.getElementById("btn" + i);

oButton.addEventListener("click", function() {
document.getElementById("fillMe").innerHTML = content;
});
}
});

关于javascript - 如何减少此代码中的变量和 if 语句的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51233244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com