我創建了一個簡單的頁面,每次按下提交時都可以更改div ID。我的問題是,這個從div_top1變化 - > div_top2,但我第二次按下按鈕,停止改變:(通過javascript更改div id
<!DOCTYPE html>
<html>
<head>
<script>
function changediv()
{
document.getElementById("div_top1").innerHTML=Date();
document.getElementById("div_top1").setAttribute("id", "div_top2");
document.getElementById("div_top2").innerHTML="teste";
document.getElementById("div_top2").setAttribute("id", "div_top1");
}
</script>
<style>
.top {
background-color: navy;
color: white;
padding: 10px 10px 10px 10px;
margin: 5px 5px 5px 5px;
}
.down {
background-color: aqua;
padding: 10px 10px 10px 10px;
margin: 5px 5px 5px 5px;
}
</style>
</head>
<body>
<div id="div_top1" class="top">This is a paragraph.</div>
<div class="down"><button type="button" onclick="changediv()">Display Date</button></div>
</body>
</html>
請問爲什麼你想改變ID?爲什麼不使用classname? ID只會改變一次,因爲第二次你不能找到第一個ID – mplungjan
你不會更安全地改變一個div的類嗎? – slinky2000
在您的代碼中,您將div_top1更改爲div_top2的那一刻就會停留在那裏。除非你把一個if切換,否則它會不斷變化。 – Edper