繁体   English   中英

转义jQuery选择器

[英]Escaping jQuery selector

为什么选择器在第一个示例中起作用,但在第二个示例中失败? 参见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>

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

发生的情况是,在第一种情况下,您必须转义\\ ,以便$()函数接收\\[ ,依此类推,以便知道将这些字符视为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/

jQuery的常见问题解答对此有一个很好的解决方案,它可以转义jQuery所需的所有字符。

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

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

另请参阅以下问题的答案:

jQuery选择器值转义

需要在jQuery选择器字符串中转义特殊字符

您无需双重逃避第二个:

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

因为确实\\[是那个符号转义了。 但是在您的第一个字符串中,您必须转义\\\\而在第二个字符串中,您必须这样做\\\\\\\\ 如果这样的话。

这不是有效的ID,因此您依赖未定义的行为。 看到这个问题 我可以建议使用数据属性来存储任意数据,而不是在ID中进行存储吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM