gpt4 book ai didi

javascript - 通过javascript更改div id

转载 作者:太空狗 更新时间:2023-10-29 14:41:47 26 4
gpt4 key购买 nike

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

最佳答案

Working FIDDLE Demo

试试这个:

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");
}


}

关于javascript - 通过javascript更改div id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16584121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com