HTML属性值中是否允许单/双引号? [英] Are single/double quotes allowed inside HTML attribute values?

查看:161
本文介绍了HTML属性值中是否允许单/双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试设置包含单引号的属性值:

  var attr_value =它不工作; 
var html =< label my_attr ='+ attr_value +'>文字< / label>;
$('body')。html(html);

然而,我得到以下结果:

 < label working =not =s =my_attr =It> Text< / label> 

我该如何解决这个问题?



是否允许在属性值中使用双引号?

解决方案

是的,两个引号在属性值中都是允许的,但是您必须使用HTML转义引用您用作属性值分隔符以及其他HTML特殊字符(如< / code>和&

 函数encodeHTML(s){
return s.split('&')。join(' &放大器;放大器; ')分裂(' < ')加入(' &安培; LT; ')分裂(' ')加入(' &安培; QUOT;'。)分裂(')加入('&#39;');
}

var html ='< label my_attr =''+ encodeHTML(attr_value)+'>文本< / label>' ;

然而,通常情况下你会更好,而不是试图破解一起记录HTML字符串,每次忘记逃跑时都会冒着错误和HTML注入(导致跨站脚本的安全漏洞),相反,我们e像DOM风格的方法,如 attr() text()和构造快捷方式:



$ p $ $('body')。append(
$('< label>',{my_attr:attr_value,text:'Text' })
);


I'm trying to set attribute value that contains a single quote:

var attr_value = "It's not working";
var html = "<label my_attr='" + attr_value + "'>Text</label>";
$('body').html(html);

However, I get the following result:

<label working="" not="" s="" my_attr="It">Text</label>

How could I fix this ?

Are double quotes allowed inside attribute values ?

解决方案

Yes, both quotes are allowed in attribute values, but you must HTML-escape the quote you're using as an attribute value delimiter, as well as other HTML-special characters like < and &:

function encodeHTML(s) {
    return s.split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;').split("'").join('&#39;');
}

var html= '<label my_attr="'+encodeHTML(attr_value)+'">Text</label>';

However, you are usually much better off not trying to hack a document together from HTML strings. You risk bugs and HTML-injection (leading to cross-site-scripting security holes) every time you forget to escape. Instead, use DOM-style methods like attr(), text() and the construction shortcut:

$('body').append(
    $('<label>', {my_attr: attr_value, text: 'Text'})
);

这篇关于HTML属性值中是否允许单/双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆