简体   繁体   English

在 <img> 标签

[英]Insert text after an <img> tag

I try to insert text after an <img> tag using javascript. 我尝试使用javascript在<img>标记后插入文本。

<div id="candy"><img src="candy.png" /> Insert text here!</div>

If I use document.getElementById('candy').innerHTML = "test"; 如果我使用document.getElementById('candy').innerHTML = "test"; the image disappears. 图像消失。

Can you help me? 你能帮助我吗?

That's because you're replacing the innerHTML with the text test . 那是因为您要用text test替换innerHTML You're not appending the text. 您没有附加文本。

Try: 尝试:

var div = document.getElementById('candy');
div.innerHTML = div.innerHTML + 'test';

Taken from here . 取自这里

Well, the img tag is part of the HTML inside the div, and if you replace the div's HTML you rewrite the img tag as well. 好吧,img标签是div内HTML的一部分,如果替换div的HTML,则也要重写img标签。

Perhaps you wanted something like this instead: 也许您想要这样的事情:

<div><img src="candy.png" /> <span id="candy">Insert text here!</span></div>

Use 采用

var div = document.getElementById('candy');
div.insertAdjacentHTML('beforeend', 'test');

Reference: https://developer.mozilla.org/en/docs/DOM/element.insertAdjacentHTML 参考: https : //developer.mozilla.org/en/docs/DOM/element.insertAdjacentHTML

That is because you javascript changes the html inside the <img> tag to test. 那是因为您的javascript更改了<img>标记内的html进行测试。 This doesn't work as <img /> is a self-closing tag. 由于<img />是一个自动关闭的标签,因此无法使用。

I believe you could you jQuery to do what you are trying to however. 我相信您可以让jQuery做您想做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM