代码之家  ›  专栏  ›  技术社区  ›  Misha Moroshko Amr Mostafa

HTML属性值中是否允许使用单引号/双引号?

  •  13
  • Misha Moroshko Amr Mostafa  · 技术社区  · 16 年前

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

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

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

    我该怎么解决?

    4 回复  |  直到 11 年前
        1
  •  20
  •   bobince    16 年前

    是的,属性值中允许两个引号,但必须对用作属性值分隔符的引号以及其他HTML特殊字符(如 < 和 &

    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>';
    

    不过,你通常会过得更好 不 attr() , text() 以及施工捷径:

    $('body').append(
        $('<label>', {my_attr: attr_value, text: 'Text'})
    );
    
        2
  •  15
  •   CodeTwice    11 年前

    有效标记:

    <label attr="This 'works'!" />
    <label attr='This "works" too' />
    <label attr="This does NOT \"work\"" />
    <label attr="And this is &quot;OK&quot;, too" />
    
        3
  •  4
  •   Marcelo Cantos    16 年前

    使用双引号作为属性分隔符:

    var html = "<label my_attr=\"" + attr_value + "\">Text</label>";
    
        4
  •  3
  •   Marco Mariani    16 年前
    var attr_value = "It&#39;s not working"