javascript jquery转义方括号选择元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8404037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery escape square brackets to select element
提问by Aakash Chakravarthy
Consider a input element
考虑一个输入元素
<input id="meta[152][value]" type="text" />
Here the input field is dynamicallygenerated. I need to select that field. So I used,
这里的输入字段是动态生成的。我需要选择那个字段。所以我用,
alert($('#meta[152][value]').val());
But this seems to be invalid. After searching I found, that the "square brackets" need to be escaped like #meta\\[152\\]\\[value\\]
但这似乎是无效的。搜索后我发现,“方括号”需要像#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
/** I need the value of id to be escaped using regex,replace or any other method to get #meta\[152\]\[value\] and not manually **/
/** 我需要使用 regex、replace 或任何其他方法来转义 id 的值来获取 #meta\[152\]\[value\] 而不是手动 **/
alert($(id).val());
Your suggestions will be helpful !
您的建议会很有帮助!
回答by Rion Williams
The following should work:
以下应该工作:
alert($('#meta\[152\]\[value\]').val());
or
或者
var id = "#meta\[152\]\[value\]";
alert($(id).val());
Conversion Function:
转换功能:
function ConvertValue(id)
{
var test = id.replace(/[[]/g,'\\[');
return "#" + test.replace(/]/g,'\\]');
}
回答by amosrivera
If you feel more comfortable without escaping you also use the attributes selector and search for the element with that id like this: $("[id='meta[152][value]']")
如果您在不转义的情况下感觉更舒服,您还可以使用属性选择器并搜索具有该 id 的元素,如下所示: $("[id='meta[152][value]']")
回答by Dennis
The simplest way is just to use the regular getElementById, which requires no escaping:
最简单的方法就是使用常规的 getElementById,它不需要转义:
document.getElementById("meta[152][value]").value;
回答by Ian Jamieson
this shoudl work for you, you almost had it:
这应该为你工作,你几乎拥有它:
$(document).ready(function() {
var id = "#meta\[152\]\[value\]";
alert($(id).val());
});
回答by idrumgood
Um, just put the escaped value right in your string.
嗯,只需将转义值放在您的字符串中。
var id = "#meta\[152\]\[value\]";
回答by Penny Liu
You can use the _.escapeRegExp
method from the Lodash library.
您可以使用_.escapeRegExp
Lodash 库中的方法。
console.log($('#' + _.escapeRegExp('meta[152][value]')).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<input id="meta[152][value]" type="text" value='Test' />