繁体   English   中英

如何将HTML标记添加到字符串中的特定位置?

[英]How to add HTML markup to a specific place in a string?

因此,我得到一个句子,在句子中间将有“ _ ”。 在“ _ ”处,我想将其替换为<span class="smallBox"></span>以便可以在此处插入一个框。

var string = "This is a string_right here";
var here = string.replace("_","<span class="smallBox"></span>");

alert(here);

但是,需要提醒的是: This is a string<span class="smallBox"></span>right here

有人可以帮忙吗?

不,没有办法使用alert()解释HTML标签,因为它是window对象的一种方法。 您可以使用诸如JQueryUI对话框之类的东西来模拟警报框,但是如果您确实需要一个警报框,则唯一可以做的就是接近您想要的行为,即打印出Unicode字符,换行符和制表符。 例如:

 // Warning: Unicode madness ahead alert( 'Alert with newlines, tabs, and bullet points\\n' + '■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■\\n' + "\\t■ Meaningless Point #1\\n" + '\\t■ Meaningless Point #2\\n' + '\\t■ Meaningless Point #3\\n' + '■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■\\n' ); 

警报框实际上并没有做太多事情,这可能是您可以期望的最好的结果。

首先,请忽略smallBox周围的引号:

var here = string.replace("_","<span class=\"smallBox\"></span>");

然后输出将是: 这是一个字符串<span class =“ smallBox”> </ span>,因为使用alert会将HTML打印为String。

暂无
暂无

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

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