[英]change div id by javascript
每次按下提交時,我都創建了一個簡單的頁面來更改div id。 我的問題是,這從div_top1 - > div_top2更改,但第二次按下按鈕,它停止更改:(
<!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>
嘗試這個:
function changediv()
{
if (document.getElementById("div_top1")) {
document.getElementById("div_top1").innerHTML=Date();
document.getElementById("div_top1").setAttribute("id", "div_top2");
}
else {
document.getElementById("div_top2").innerHTML="teste";
document.getElementById("div_top2").setAttribute("id", "div_top1");
}
}
問題不在於改變身份 - 這是你每次都以兩種方式改變它。 你需要一個if條件。 您還應該使用.id來更改id而不是setAttribute() - 我在過去(多年前)使用setAttribute進行id更改時遇到了一些問題。
演示: http : //jsfiddle.net/x2nPY/
function changediv() {
if (document.getElementById("div_top1")) {
document.getElementById("div_top1").innerHTML = Date();
document.getElementById("div_top1").id = "div_top2";
} else {
document.getElementById("div_top2").innerHTML = "teste";
document.getElementById("div_top2").id = "div_top1";
}
}
您可以使用if,例如,如果您想要切換它或每次提交時更改,如:
function changediv() {
if (document.getElementById("div_top1"))
{
document.getElementById("div_top1").innerHTML=Date();
document.getElementById("div_top1").setAttribute("id", "div_top2");
}
else
{
document.getElementById("div_top2").innerHTML="teste";
document.getElementById("div_top2").setAttribute("id", "div_top1");
}
}
請參閱小提琴演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.