我有一个 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 代码的注释中。
最佳答案
// Q1. Why answer shows only 1 backslash while I used 2 in regex
因为您用作替代的字符串中只有一个反斜杠,因为反斜杠在字符串文字中很特殊。要在选择器中添加实际的反斜杠,您需要在字符串文字中使用 \\
。但是您的 escape
函数是正确的,因为您在实际的正则表达式中只需要一个。
// Q2. Does not work while
escapedId === 'i\:have\:colons'
. How and why ?
console.log($('#' + 'i\:have\:colons').length);
同样的原因,选择器中没有反斜杠。字符串文字中的 \:
只是 :
。您需要转义反斜杠:
console.log($('#' + 'i\\:have\\:colons').length);
用于选择这些元素的选项:
使用
escape
函数正确转义id
值。使用
getElementById
:$(document.getElementById("i:have:colons"))
使用属性选择器:
$('[id="i:have:colons"]')
但这会更慢(尽管重要的可能性很低),因为 jQuery 不会将其优化为
getElementById
调用。
关于jquery - 在 Sizzle/jQuery 中选择 Id 带有冒号的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25484580/