jquery转义方括号来选择元素 [英] jquery escape square brackets to select element

查看:210
本文介绍了jquery转义方括号来选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个输入元素

<input id="meta[152][value]" type="text" />

这里输入字段是动态生成的。我需要选择该字段。所以我使用

Here the input field is dynamically generated. I need to select that field. So I used,

alert($('#meta[152][value]').val());

但这似乎是无效的。搜索后,我发现,方括号需要像#meta\\ [152\\] \\ [value\\]

But this seems to be invalid. After searching I found, that the "square brackets" need to be escaped like #meta\\[152\\]\\[value\\]

那么怎么做呢?
我目前使用这个代码,

So how to do that ? I currently use this code,

var id = "#meta[152][value]" // (I get this value by another method) I need the escaping to be done here. So that i can use as

/ **我需要使用正则表达式转义id的值,替换或任何其他方法
获取#meta\ [152\] \ [value\]
而不是手动** /

/** I need the value of id to be escaped using regex,replace or any other method to get #meta\[152\]\[value\] and not manually **/

alert($(id).val());

您的建议将会有帮助!

推荐答案

以下内容应该起作用:

alert($('#meta\[152\]\[value\]').val());

var id = "#meta\[152\]\[value\]";
alert($(id).val());

工作示例

转换功能

function ConvertValue(id)
{
    var test = id.replace(/[[]/g,'\\\\[');
    return "#" + test.replace(/]/g,'\\\\]'); 
}

转换示例

Conversion Example

这篇关于jquery转义方括号来选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆