哪个性能更好?如果语句更具可读性,但是如果我在数组(数据库式)中创建值并让我的 for 循环根据当前索引调用函数,这使得进一步编辑变得更容易。
var msg = [
"You are now viewing Tab number one",
"You are now viewing Tab number two",
"You are now viewing Tab number three",
"You are now viewing Tab number four"
]
var button = document.getElementsByTagName("button")
for (var i = 0, len = button.length; i < len; ++i) {
(function(index) {
button[i].addEventListener("click",
function() {
document.getElementById("msg").innerHTML = msg[index];
});
})(i);
}
<button>Tab1</button>
<button>Tab2</button>
<button>Tab3</button>
<button>Tab4</button>
<br>
<p id="msg">Message here</p>
var button = document.getElementsByTagName("button")
for (var i = 0, len = button.length; i < len; ++i) {
(function(index) {
button[i].addEventListener("click",
function() {
if (index==0){
document.getElementById("msg").innerHTML = "You are now viewing Tab number one";
}
if (index==1) {
document.getElementById("msg").innerHTML = "You are now viewing Tab number two";
}
if (index==2) {
document.getElementById("msg").innerHTML = "You are now viewing Tab number three";
}
if (index==3) {
document.getElementById("msg").innerHTML = "You are now viewing Tab number four";
}
});
})(i);
}
<button>Tab1</button>
<button>Tab2</button>
<button>Tab3</button>
<button>Tab4</button>
<br>
<p id="msg">Message here</p>
喵喵时光机
MYYA
陪伴而非守候
相关分类