.html()不对传递的值进行编码

时间:2012-02-19 15:23:57

标签: jquery html encoding

我需要将每个字符保持传递给.html(),即未编码。例如,.html('>')将小于号的字符保存为>,而不是&lt;。我该怎么做?理想情况下,解决方案将应用到所有“特殊”字符,例如<&

<h1 id="my-title"></h1>

// JavaScript / jQuery code.
$('#my-title').html('>');
...
...
// Somewhere else in the code, I need to retrieve the value back by calling
// var v = $('#my-title').html();

3 个答案:

答案 0 :(得分:2)

使用text()代替html()

var v = $('#my-title').text();

答案 1 :(得分:1)

而不是.html()使用.text()来保存和检索值。

$('#my-title').text('>');
var v = $('#my-title').text();

alert( v );   // alerts >

请注意,您还需要使用.text()来保存值。有<>成为编码的原因......

答案 2 :(得分:0)

text不会对值进行编码:

$('#my-title').html('>');
alert($('#my-title').text() + ' not encoded');
alert($('#my-title').html() + ' encoded');
​

JSFiddle DEMO

相关问题