【问题标题】:Escaping jQuery selector转义 jQuery 选择器
【发布时间】:2011-11-22 17:52:14
【问题描述】:

为什么选择器在第一个示例中有效,但在第二个示例中失败? 见jsfiddle

<div id="hello[1][2]_world">&nbsp;</div>
<textarea id="console"></textarea>

<script>
   $(document).ready(function() {

      //first example
      $('#hello\\[1\\]\\[2\\]_world').html('01234'); //everything is OK

      //second example
      var iid = 'hello[1][2]_world';    
      iid = iid.replace(/[#;&,.+*~':"!^$[\]()=>|\/]/g, "\\\\$&");
      $('#console').val(iid); //see in textarea, the same string as from first    

      $('#'+iid).html('56789'); //not working! whyyyyyyyy? :)

   });    
</script>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    第一个字符串是“实际上”'#hello\[1\]\[2\]_world'

    发生的情况是,您必须在第一种情况下转义 \s,以便 $() 函数接收 \[ 等等,以便它知道应该将这些字符视为 id 的一部分。

    在第二种情况下,您将创建一个字符串 hello\\\\[1\\\\]\\\\[2\\\\]_world(因为您在替换中有 4 个反斜杠!)在反斜杠被转义后变为 hello\\[1\\]\\[2\\]_world

    您可以通过在末尾添加这些行来确认这一点(查看 JS 控制台):

    console.log( iid );
    console.log( 'hello\\[1\\]\\[2\\]_world' );
    

    http://jsfiddle.net/qSpaK/7/

    【讨论】:

      【解决方案2】:

      第二个不需要双重转义:

      <div id="hello[1][2]_world">&nbsp;</div>
      <textarea id="console"></textarea>
      
      <script>
         $(document).ready(function() {
      
            //first example
            $('#hello\\[1\\]\\[2\\]_world').html('01234'); //everything is OK
      
            //second example
            var iid = 'hello[1][2]_world';    
          iid = iid.replace(/[#;&,.+*~':"!^$[\]()=>|\/]/g, "\\$&");
            $('#console').val(iid); //see in textarea, the same string as from first    
      
            $('#'+iid).html('56789'); //not working! whyyyyyyyy? :)
         });    
      </script>
      

      因为真的\[ 是那个符号转义了。但是在您的第一个字符串中,您必须转义\\,而在第二个字符串中您正在执行此\\\\。如果这有意义的话。

      【讨论】:

        【解决方案3】:

        jQuery's FAQ 有一个很好的解决方案,可以转义 jQuery 需要的所有字符。

        我喜欢他们建议的这个 nullsafe 版本:

        function jqid (id) {
          return (!id) ? null : '#' + id.replace(/(:|\.|\[|\]|,)/g, '\\$1');
        }
        

        还可以查看这些问题的答案:

        jQuery selector value escaping

        Need to escape a special character in a jQuery selector string

        【讨论】:

          【解决方案4】:

          这不是一个有效的 ID,因此您依赖于未定义的行为。见this question。我可以建议使用data attributes 存储任意数据而不是在 ID 中存储吗?

          【讨论】:

          猜你喜欢
          • 2010-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-28
          • 2016-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多