插入< br/>在Javascript中的字符串中 [英] Insert <br /> in a String in Javascript

查看:83
本文介绍了插入< br/>在Javascript中的字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个很长的compund字符串:

Let's say, I have a pretty long compund String:

var result = string1 + " - " + string2 + " - " + string3;

,然后通过创建新的列表项在网站中显示字符串:

and I display the String in the Website by creating a new list item:

var listElement = document.createElement("li"),
container = document.querySelector("#resultlist"); //I have a <ul id="resultlist">
listElement.appendChild(document.createTextNode(result));
container.appendChild(listElement);

如何在例如字符串的第二部分和第三部分?所以,我需要这样的东西:

How can I add a <br /> tag between e.g. the second and the third part of the String? So, I need something like this:

result = string1 + " - " + string2 + " <br /> " + string3;

(但是这种尝试只会显示标签).
我也已经尝试过\ n命令,但这对网站输出没有影响.

(But that attempt just displays the tag).
I also tried the \n command already, but this had no effect on the website output.

感谢您的帮助!

推荐答案

<br />标记是HTML(至少您希望将其解释为HTML).顾名思义,您不能使用createTextNode()将HTML添加到页面.您应该改用innerHTML.

The <br /> tag is HTML (at least you want it to be interpreted as HTML). You cannot add HTML to pages using createTextNode(), as the name suggests. You should use innerHTML instead.

var result = "First String" + " - " + "Second String" + " <br /> " + "Third String",
listElement = document.createElement("li"),
container = document.querySelector("#resultlist"); //I have a <ul id="resultlist">
listElement.innerHTML = result;
container.appendChild(listElement);

<ul id="resultlist"></ul>

这篇关于插入&lt; br/&gt;在Javascript中的字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆