繁体   English   中英

在innerHTML中在文本和图像之间添加br标签

[英]Adding br tag in innerHTML between text and image

在我的JavaScript程序中,我已经创建了div并通过使用innerHTML在div中添加了图像和一些硬编码的文本。 但是我试图在文本和图像之间添加动态br标签。 应该先显示文本,然后要换行,然后再显示图像。 因此创建了br并添加了br,但以某种方式无法正常工作。 谁能纠正我?

码:

 function useInnerHTML() { var movieText2 = prompt("One of my favourite movies"); var textNode = document.createTextNode(movieText2); ele.appendChild(textNode); document.body.appendChild(ele); var newDiv2 = document.createElement("div"); var br = document.createElement("br"); newDiv2.className = "green"; var pic = "A picture is worth a thousand words"; var text2 = '<img src=\\'https://i.stack.imgur.com/meXYL.png\\'>'; newDiv2.innerHTML = pic + text2; document.body.appendChild(newDiv2); document.body.appendChild(br); } useInnerHTML(); 
 .pink { background-color: pink; } .green { background-color: #71e887; } 

我的输出:

![输出] [1]

只需使用

pic = "A picture is worth a thousand words <br>";

因为使用.innerHTML不会使<br>标记转义,而是将其作为断线元素实际嵌入到HTML中。


要么

使用模板字符串和insertAdjacentHTML

 function addNewMovie() { var movieName = prompt("One of my favourite movies").trim(); // Trim it! if(!movieName) return; // do nothing if empty! var movieTemplate = ` <div class="movie"> <h1>${movieName}</h1> <div class="green"> A picture is worth a thousand words<br> <img src='//placehold.it/100x100/0bf'> </div> </div> `; document.body.insertAdjacentHTML("beforeend", movieTemplate); } 
 <button onclick="addNewMovie()">ADD NEW MOVIE</button> 

...更干净,更好

您要在<br>后添加<br> ,尝试这样做:

newDiv2.innerHTML = pic + br + text2;

document.body.appendChild(newDiv2);

暂无
暂无

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

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