开发者

Handling a input with HTML inside its value (using jQuery)

I created a small function similar to a edit-in-place plugin.

What it does:

  • gets the html content of a element on click: var editable = $(this).html();
  • creates the text input field (or gets it if it exists):

    var input = ($('input', this).length > 0) ? $('input', this) : $('<input type="text" value="' + editable + '" />'),
    
  • replaces the element text with the input: $(this).empty().append(input);

This works but only if the editable text doesn't contain non-encoded HTML characters.

If it has HTML characters like < >, they g开发者_如何学编程et converted in the 2nd step to HTML code, and mess up the input element...

I tried to escape them by using:

editable = $('<div/>').text($(this).html()).html()

but then I get a text input with escaped HTML lol :)

What can I do?


You can HTML-escape a string so that it can be included in an HTML attribute value like this:

var escaped = string.replace(/</g, '&lt;').replace(/'/g, '&#39;').replace(/"/g, '&#34;');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜