jQuery选择器和反斜杠 [英] jQuery selectors and backslashes

查看:295
本文介绍了jQuery选择器和反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个dom元素,其中包含全限定名作为id属性的一部分;

I have a dom element that contains a fully qualified name as part of the id attribute;

<div id="domain\element\div">My Div</div>

让jQuery通过ID选择元素似乎是不可能的.这是我的实验;

It seems impossible to get jQuery to select the element by ID. Here's my experiment;

var $e1 = $('#domain\\\element\\\div');
var $e2 = $('#domain\\element\\div');
var $e3 = $(document.getElementById('domain\\\element\\\div'));
console.log($e1);
console.log($e2);
console.log($e3);

控制台的输出将前两个显示为空,而第三个显示;

The output of the console displays the first two as empty while the third works;

[]
[]
<div id=​"domain\element\div">​TODO write content​</div>​

我正在使用jQuery 1.5.2.这是jQuery本身的错误还是我的选择器字符串错误?

I am using jQuery 1.5.2. Is this a bug with jQuery itself or are my selector strings wrong?

推荐答案

如果您可以在HTML代码中更改ID,请为ID找到除反斜杠\之外的其他分隔符,以便为您的选择器(请参见此处).下划线_会很好.

If you can change the ID within your HTML code, find some other separator than a backslash \ for your ID so that you can make a valid ID for your selector (see here). An underscore _ would be good.

如果您无法更改HTML,则jQuery仍可以在ID和ID选择器中使用反斜杠.除此之外,您需要使用四个反斜杠来匹配ID选择器中的每个文字反斜杠:

If you can't alter the HTML, jQuery can still work with backslashes in IDs and ID selectors. Except, you'll need to use four backslashes to match each literal backslash in your ID selector:

$('#domain\\\\element\\\\div')

您可以通过以下方式实现这一目标

You achieve this by

  1. 获取ID:

  1. Taking the ID:

domain\element\div

  • 添加#符号并为选择器转义反斜杠:

  • Adding the # symbol and escaping the backslashes for the selector:

    #domain\\element\\div
    

  • 通过将每对反斜杠加倍来使它们在JavaScript字符串中使用(也请注意引号):

  • Escaping each pair of backslashes for use in JavaScript strings by doubling them (also notice the quotes):

    '#domain\\\\element\\\\div'
    

  • 然后如上所述将字符串传递到$().

    jsFiddle

    这篇关于jQuery选择器和反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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