【发布时间】: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