我有一个带有文本的 div 和一个用作链接的图标。我希望文本在按钮单击时更改而不影响图标。
innerHTML 和innerText 都使图标消失。
<div class="title" id='title'>Text I want to change
<a href="https://link.com" target=_blank>
<img src="icon.svg"id='icon'>
</a>
</div>
<button id='button'>click here to change text<button>
Run Code Online (Sandbox Code Playgroud)
function changeText(text) {
document.getElementById("title").innerText=text
}
const button = document.getElementById('button');
button.addEventListener('click', () => changeText('the new text I want'));
Run Code Online (Sandbox Code Playgroud)
文本正确更改但图标消失。将图标移到 div 之外当然可以解决问题,但我不想这样做。任何帮助真的很感激。
使用 element.innerText() 您实际上是覆盖了 div 的全部内容 - 包括其他 html 元素,例如锚标记。
有一个孩子附加到您的 div 实际保存您的文本。您可以通过document.getElementById("title").firstChild以及它的.data属性来引用它。
function changeText(text) {
document.getElementById("title").firstChild.data = text;
}
const button = document.getElementById('button');
button.addEventListener('click', () => changeText('the new text I want '));Run Code Online (Sandbox Code Playgroud)
<div class="title" id='title'>Text I want to change
<a href="https://link.com" target=_blank><img src="icon.svg" id='icon'></a>
</div>
<button id='button'>click here to change text<button>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2040 次 |
| 最近记录: |