我创建了一个简单的页面,每次按下提交时都可以更改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