代码之家  ›  专栏  ›  技术社区  ›  Tony Borf

Jquery在属性中嵌入引号

  •  1
  • Tony Borf  · 技术社区  · 17 年前

    我有一个从数据库填充的自定义属性。此属性可以包含这样的嵌入单引号,

      MYATT='Tony\'s Test'
    

     $('#MY_DESC').val($(recdata).attr('MYATT'));
    

    MY_DESC是对话框中的文本字段。当我显示对话框时,我在字段中看到的是

    托尼\

    我需要看到的是,

    如何修复此问题,以便可以看到整个字符串?

    4 回复  |  直到 17 年前
        1
  •  3
  •   Ken Browning    17 年前

    MYATT='Tony&#x27s Test'
    

    我没有用HTML规范验证这一点,但是 wikipedia 条目上写着:

    The ability to "escape" characters in this way allows for the characters < and & (when written as &lt; and &amp;, respectively) to be interpreted as character data, rather than markup. For example, a literal < normally indicates the start of a tag, and & normally indicates the start of a character entity reference or numeric character reference; writing it as &amp; or &#x26; or &#38; allows & to be included in the content of elements or the values of attributes. The double-quote character ("), when used to quote an attribute value, must also be escaped as &quot; or &#x22; or &#34; when it appears within the attribute value itself. The single-quote character ('), when used to quote an attribute value, must also be escaped as &#x27; or &#39; (should NOT be escaped as &apos; except in XHTML documents) when it appears within the attribute value itself. However, since document authors often overlook the need to escape these characters, browsers tend to be very forgiving, treating them as markup only when subsequent text appears to confirm that intent.

        2
  •  1
  •   Thinker    17 年前

    如果不是,我建议逃避这个值。

        3
  •  0
  •   blparker    17 年前

    在设置文本字段的值之前,可以尝试对字符串运行正则表达式,以删除字符串中的所有反斜杠。

        4
  •  0
  •   FerrousOxide    17 年前

    如果您这样做:

    警报($(recdata.attr('MYATT'));

    您将看到“Tony\”的相同结果,这意味着浏览器没有正确使用该值。在这种情况下,转义的\'值不起作用。

    您是否有办法在生成这些值时对其进行编辑?在渲染之前,是否可以解析它们以包含转义值?