【问题标题】:Selecting an element with Id having colons in Sizzle/jQuery在 Sizzle/jQuery 中选择带有冒号的 Id 元素
【发布时间】:2014-08-25 19:35:28
【问题描述】:

我有一个 HTML,其中一些元素的 id 带有冒号。例如,

<div id="i:have:colons">Get my selector!!</div>
<my:another:test> This time with tag names </my:another:test>

我想使用 jQuery 选择这些元素。这是我的几次尝试和Jsbin Demo

function escape(id) {
  return id.replace( /(:|\.|\[|\])/g, '\\$1');
}

var id = "i:have:colons";

// Does not work
console.log($('#' + id).length);

// Works
console.log($("#i\\:have\\:colons").length);

var escapedId = escape(id);

// Q1. Why answer shows only 1 backslash while I used 2 in regex
console.log(escapedId); //'i\:have\:colons'

// Works
console.log($('#' + escapedId).length);

// Q2. Does not work while escapedId === 'i\:have\:colons'. How and why ?
console.log($('#' + 'i\:have\:colons').length);

在 T.J 回答后编辑

var tag = 'my:another:test';

console.log('Testing tag name now----');

console.log($(tag).length);

var tag2 = tag.replace(/[:]/g, '\\\\:');

// Does not work with tagnames but this works with Id
console.log($(tag2).length);

var tag3 = tag.replace(/[:]/g, '\\:');

// Q3. Why does this work with tagnames but not with ids ?
console.log($(tag3).length);

我的问题在 JS 代码中的 cmets 中。

【问题讨论】:

    标签: jquery escaping colon sizzle


    【解决方案1】:

    // 第一季度。为什么答案只显示 1 个反斜杠,而我在正则表达式中使用了 2 个

    因为您用作替代的字符串中只有 一个 反斜杠,因为反斜杠在字符串文字中是特殊的。要在选择器中添加实际的反斜杠,您需要在字符串文字中使用 \\。但是您的 escape 函数是正确的,因为您在实际的正则表达式中只想要一个。

    //第二季度。 escapedId === 'i\:have\:colons' 时不起作用。如何以及为什么?

    console.log($('#' + 'i\:have\:colons').length);

    同样的原因,选择器中没有反斜杠。字符串文字中的\: 就是:。您需要转义反斜杠:

    console.log($('#' + 'i\\:have\\:colons').length);
    

    选择这些元素的选项:

    1. 使用 escape 函数正确转义 id 值。

    2. 使用getElementById:

       $(document.getElementById("i:have:colons"))
      
    3. 使用属性选择器:

       $('[id="i:have:colons"]')
      

      但这会更慢(尽管它的可能性很低),因为 jQuery 不会将其优化为 getElementById 调用。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 2011-01-24
    • 2010-09-12
    • 2011-07-29
    • 2012-02-23
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多