[英]jQuery Selecting elements by dynamic name with square brackets (fiddle incl)
How can I make this fiddle work: http://jsfiddle.net/gAHwW/ 我如何使这个小提琴起作用: http : //jsfiddle.net/gAHwW/
function $escape(string) {
return string.replace(/\\(\[|\]\\)/g,'\\\\$1');
}
$(function() {
$('input[type="button"]').click(function() {
alert($escape( $(this).attr('id') )); // to show you what the escape does
$('#' + $(this).attr('id')).hide(); // doesn't work
$('#' + $escape( $(this).attr('id') )).hide(); // doesn't work
$('#alsosquare[]').hide(); // doesn't work
//$(this).hide(); // works
//$('#alsosquare\\[\\]').hide(); // works
});
});
I need to select elements by their name/id dynamically, and their names/ids can have square brackets. 我需要根据其名称/ id动态选择元素,并且其名称/ id可以带有方括号。
Thanks! 谢谢!
You simply have to double escape( \\\\
) the brackets. 您只需要加倍转义(
\\\\
)括号即可。
Here's a demo: http://jsfiddle.net/k3YyX/ 这是一个演示: http : //jsfiddle.net/k3YyX/
Here's a quote from the jQuery docs : 这是jQuery文档的引文:
If you wish to use any of the meta-characters (such as !"#$%&'()*+,./:;<=>?@[\\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\\\ . For example, if you have an element with id="foo.bar" , you can use the selector $("#foo\\\\.bar") .
如果您希望使用任何元字符(例如!“#$%&'()* +,。/ :; <=>?@ [\\] ^`{|}〜 )作为的文字部分一个名称,必须用两个反斜杠转义该字符: \\\\例如,如果您的元素具有id =“ foo.bar” ,则可以使用选择器$(“#foo \\\\。bar”) 。
Update: 更新:
Here's your fiddle, in working condition: http://jsfiddle.net/gAHwW/1/ 这是您的提琴琴,处于工作状态: http : //jsfiddle.net/gAHwW/1/
All I did was replace '\\\\\\\\$1'
with this '\\\\$1'
in your $escape
function. 我所做的就是在
$escape
函数中用'\\\\$1'
替换'\\\\\\\\$1'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.