简体   繁体   English

如何在jQuery中动态创建混合HTML内容

[英]How to dynamically create mixed HTML content in jQuery

Considering I want to create this HTML dynamically: 考虑到我想动态创建此HTML:

<li><img src="a"/>some text</li>

Some text is a text string that is potentially unsafe, let's say is stored in variable 'some_text'. 某些文本是可能不安全的文本字符串,比如说存储在变量“ some_text”中。

The idea is to call $('<li>').append($('<img>').attr({src:"a"}), ... ); 这个想法是调用$('<li>').append($('<img>').attr({src:"a"}), ... );

Using $(some_text) is bad idea because it's unsafe. 使用$(some_text)是一个坏主意,因为它是不安全的。

Using text(some_text) doesn't work because the text is not an only child of an element. 使用text(some_text)无效,因为文本不是元素的唯一子元素。

I do not want to wrap the text into a <span> 我不想将文本换成<span>

I do not want to invent/use a function that sanitizes or escapes the string 我不想发明/使用清理或转义字符串的函数

有很多方法,但可能最简单的方法是先将文本内容添加到li元素,然后在图像前添加正确的顺序。

$('<li>').text(some_text).prepend($('<img>').attr({src:"a"}), ... );

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

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