javascript - jQuery 通过带方括号的动态名称选择元素(fiddle incl)

标签 javascript jquery

我怎样才能让这个 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/

相关文章:

javascript - 如何在 D3.js 中垂直包装 SVG 中的文本?

jquery - 我可以使用 jquery 拦截 marketo 登陆页面表单提交吗

php - 向上滑动 DIV 容器

javascript - 快速点击时未调用 AJAX 请求

javascript - 将 JSON 对象渲染成 HTML,渲染函数不渲染深层对象

javascript - 获取此下文本的标签

javascript - 选择具有相同 URL id 的类

javascript - Batman.js View 中的动态类名称

javascript - 通过localStorage实现StorageEvent

javascript - 从数组中获取特定值并将值转换为另一个数组