這裏我在打印某些基於條件的圖像時遇到問題。出於這個原因,我使用了一個for循環,並在裏面使用了getElementById。但問題是它只是最後一個。Javascript getElementById for循環
我想基於數組條件打印五次。
下面是示例代碼
var arr = ["false", "false", "true", "false", "true"];
for (var i = 0; i < arr.length; i++) {
console.log("Hello")
if (arr[i] === "true") {
console.log("true")
document.getElementById("imageId").src = "green.png";
} else
document.getElementById("imageId").src = "red.png";
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="col-sm-2">
<div>
<img id="imageId" src="" alt="HTML5 Icon" style="width:50px;height:50px;">
</div>
<span>server1</span>
</div>
</div>
</div>
</div>
你有什麼問題? –
您正在覆蓋src 5次? – sinisake
它只取最後一個值,因爲這是循環數組時循環的最後一個值。你期望發生什麼? –