I realise that I can prepend stuff to an element using:
$(...).prepend(myText);
However, if myText
is, le开发者_如何学JAVAt’s say, "<span>"
, I actually want that text to appear, but .prepend()
would instead prepend an empty span element. What is the recommended way to solve this? Do I really have to HTML-escape the text manually or is there something more elegant?
You can create a textnode and put the contents there and prepend
that:
$('div').prepend(document.createTextNode("<span>"));
example: http://jsfiddle.net/niklasvh/gCKHe/
You can use the text
function instead of prepend
, and simply add the original text to the end of the new text:
$("#elementID").text("<span>" + $("#elementID").text());
HTML entities are ok, in my opinion:
$(...).prepend('<span>');
You may automate the entities with the tip found at http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
$(...).prepend($('<div/>').text('<span>').html());
If you also want to create PHP's function htmlentities in Javascript, you may use the code available at PHP-JS project: http://phpjs.org/functions/htmlentities:425
Or you may simplify by wrapping the previous tip in a function:
function htmlentities(string) {
return $('<div/>').text(string).html();
}
In both cases, you would use the htmlentities function like this:
$(...).prepend(htmlentities('<span>'));
You could implement HTML encode (and decode) functions, like this accepted answer: HTML-encoding lost when attribute read from input field
and then do:
$(...).prepend(htmlEncode(myText));
精彩评论