gpt4 book ai didi

javascript - javascript 中的 getElementByID [对象 HTMLSpanElement]

转载 作者:行者123 更新时间:2023-11-28 15:21:29 24 4
gpt4 key购买 nike

我遇到以下问题...我想用 span 的其他文本替换 div 的文本。

所以我尝试了这个:

<main>
<span id="export_text">This text should be exported</span><br>
<div id="import_text">Here the new text should be after pressing the button</div><hr>
<a onclick="run()"><button>run</button></a>
</main>

<script type="text/javascript">
function run() {
document.getElementById('import_text').innerHTML = document.getElementById('export_text');
}
</script>

现在,如果我按下按钮,div 中的文本将被替换为 [object HTMLSpanElement] 而不是 span 中的文本。我在这里做错了什么?

谢谢!

最佳答案

只需在导出文本选择器的末尾添加 .innerHTML:

function run() {
document.getElementById('import_text').innerHTML = document.getElementById('export_text').innerHTML;
}

我还强烈建议你在 JS 中移动你的事件:

document.getElementById("myBtn").addEventListener("click", run);

更新的 HTML:

<main> <span id="export_text">This text should be exported</span>
<br>
<div id="import_text">Here the new text should be after pressing the button</div>
<hr> <a><button id="myBtn">run</button></a>
</main>

JSFiddle:http://jsfiddle.net/ghorg12110/n4cwem28/1/

关于javascript - javascript 中的 getElementByID [对象 HTMLSpanElement],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31204099/

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