[英]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? 你能帮助我吗?
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.