我怎样才能让这个 fiddle 工作: 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
});
});
我需要根据元素的名称/id 动态选择元素,并且它们的名称/id 可以带有方括号。
谢谢!
最佳答案
您只需将括号双转义(\\
)即可。
这是一个演示:http://jsfiddle.net/k3YyX/
<小时/>这里引用 the jQuery docs :
<小时/>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").
更新:
这是你的 fiddle ,处于工作状态:http://jsfiddle.net/gAHwW/1/
我所做的只是在您的 $escape
函数中将 '\\\\$1'
替换为 '\\$1'
。
关于javascript - jQuery 通过带方括号的动态名称选择元素(fiddle incl),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10695377/