Append HTML-escaped text: jQuery

烂漫一生 提交于 2020-01-20 05:03:07

问题


I'm used to using jQuery's .append() method to add text or HTML onto the end of a pre-existing element. I'm currently using jQuery's .text() to escape strings that could potentially contain HTML. Unfortunately, there doesn't seem to be a jQuery method that will append the results of the .text() method to an element instead of replacing its contents.

Is there a way to append, instead of replace, this escaped text to an element? Or is there a better way to escape strings containing HTML?

Thanks.

- EDIT -

A little more context: I'm building an HTML string dynamically, and so I'll need to be able to add multiple elements with escaped content programmatically.


回答1:


You could create a dummy element to hold the result of .text() which can then be appended to your destination element:

$('<div/>').text('your <span>html</span> string').appendTo(...);



回答2:


As I have tried many ways, I think the following method is the cleanest way to add text to whatever node you want. no stock tag needed, only plain text, which will help to avoid potential problems

$(document.createTextNode("SomePlainText")).appendTo(p);



回答3:


You could just use

$(whatever).text($(whatever).text() + whatever_you_want_to_append);

EDIT for the fiddle in my comment, try this:

for ( /* some looping parameters */ ) {
    $('<li></li>') // create an li
        .text(stringWithHtml) // pass it the text, as text not html
        .appendTo('#thisIsWhatINeed'); // append it where you want it
}

jsFiddle



来源:https://stackoverflow.com/questions/11957529/append-html-escaped-text-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!