我正在尝试设置包含单引号的属性值:
var attr_value = "It's not working";
var html = "<label my_attr='" + attr_value + "'>Text</label>";
$('body').html(html);
Run Code Online (Sandbox Code Playgroud)
但是,我得到以下结果:
<label working="" not="" s="" my_attr="It">Text</label>
Run Code Online (Sandbox Code Playgroud)
我怎么能解决这个问题?
属性值中是否允许使用双引号?
bob*_*nce 20
是的,属性值中允许使用两个引号,但是您必须将您正在使用的引用作为属性值分隔符进行HTML转义,以及其他HTML特殊字符,例如<和&:
function encodeHTML(s) {
return s.split('&').join('&').split('<').join('<').split('"').join('"').split("'").join(''');
}
var html= '<label my_attr="'+encodeHTML(attr_value)+'">Text</label>';
Run Code Online (Sandbox Code Playgroud)
但是,通常情况下,不要尝试从HTML字符串中一起破解文档会更好.每次忘记逃避时,都会冒错误和HTML注入(导致跨站点脚本安全漏洞).相反,使用DOM风格的方法,如attr(),text()和施工快捷方式:
$('body').append(
$('<label>', {my_attr: attr_value, text: 'Text'})
);
Run Code Online (Sandbox Code Playgroud)
Cod*_*ice 15
您可以在双引号内使用单引号或在单引号内使用双引号.如果要在双引号内使用单引号内的单引号或双引号,则必须对它们进行HTML编码.
有效标记:
<label attr="This 'works'!" />
<label attr='This "works" too' />
<label attr="This does NOT \"work\"" />
<label attr="And this is "OK", too" />
Run Code Online (Sandbox Code Playgroud)