简体   繁体   English

javascript 中的 html_entities

[英]html_entities in javascript

Here i have a textbox in which user inputs html tags like <h1>hello</h1> then i append that text to a td with这里我有一个文本框,用户在其中输入 html 标签,如<h1>hello</h1>然后我 append 将文本发送到 td

 var text = $('textbox').val();
 $('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

Now what i want is the text in the td should come text as entered <h1>hello</h1> and not hello with h1 tag现在我想要的是 td 中的文本应该是输入的文本<h1>hello</h1>而不是带有 h1 标签的 hello

I tried escape and unscape but it didnt helped我尝试了逃生和逃生,但没有帮助

Used encode function from here HTML-encoding lost when attribute read from input field使用的编码 function 从这里HTML-encoding lost when attribute read from input field

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

 var text = htmlEncode($('textbox').val());
 $('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

Here's a plain JavaScript function without the jQuery overkill:这是一个普通的 JavaScript function 没有 jQuery 矫枉过正:

function htmlEncode(str) {
    return str.replace(/[<>&"']/g, function($0) { return "&" + {"<":"lt",">":"gt","&":"amp",'"':"quot","'":"#39"}[$0] + ";"; });
}

This looks for any occurrence of < , > , & , " , and ' , calls the function that then looks up the matched character and returns the corresponding character reference.这将查找<>&"'的任何出现,调用 function 然后查找匹配的字符并返回相应的字符引用。

You could try replacing the < by &lt;您可以尝试将 < 替换为 &lt; and > by &gt;和 > 由 &gt;

var text = $('textbox').val();
text = text.replace(/</g,'&lt;').replace(/>/g,'&gt;');
$('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

You can test it yourself here: http://jsfiddle.net/W7RWA/你可以在这里自己测试: http://jsfiddle.net/W7RWA/

You need to set the node value with the val() method :您需要使用val() 方法设置节点值:

// Untested
var text = $('textbox').val();
var tr = $('<tr><td style="padding:0px 12px;color:black"></td></tr>');
tr.find("td").val(text);
$('table').append(tr);

PHPJS is an excellent resource for these sorts of "How can I use this PHP function in Javascript?" PHPJS是这类“如何在 Javascript 中使用这个 PHP function?”的优秀资源questions.问题。

Javascript htmlentities() Javascript htmlentities()

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

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