[英]jQuery - getting error for square brackets in name attribute
I know there are already a lot of posts in SO regarding this issue. 我知道在SO中已经有很多关于此问题的帖子。 But none of them works for my case.
但是它们都不适合我的情况。
I've multiple select inputs with the following naming format: 我有多个具有以下命名格式的选择输入:
select name="violationCategory[${theCount.count-1}].subCategory"
which translates to something like: 相当于:
select name="violationCategory[0].subCategory"
select name="violationCategory[1].subCategory"
.. so on
I've to apply a particular class on these select inputs if some condition is fulfilled. 如果满足某些条件,则必须在这些选择输入上应用特定的类。 So, I try replacing the square brackets with something like this:
因此,我尝试将方括号替换为以下内容:
if(key.indexOf("[") >= 0){
key = $.trim(key).replace("name=^[","name=^\\[");
key = $.trim(key).replace("].","\\].");
alert(key);
$("#" + formId + " select[name=" + key + "]").addClass('inputBoxError');
}
The alert prints: 警报打印:
violationCategory[1\].subCategory]
and I get the error: 我得到错误:
Uncaught Error: Syntax error, unrecognized expression: #referralViolationForm select[name=violationCategory[1\].subCategory]
When I change the code to: 当我将代码更改为:
key = $.trim(key).replace("].","\].");
alert prints: 警报打印:
violationCategory[1].subCategory]
and I get the error: 我得到错误:
Uncaught Error: Syntax error, unrecognized expression: #referralViolationForm select[name=violationCategory[1].subCategory]
So, basically it works neither ways. 因此,从根本上讲,它都不起作用。
Can anyone help me out as to how to escape the square brackets. 谁能帮助我解决如何逃避方括号。
Your attribute value should be wrapped within ""
, there is no need to escape the [
or ]
您的属性值应包含在
""
,无需转义[
或]
$('#' + formId + ' input[name="' + key + '"]').addClass('inputBoxError');
So the translated selector should be 所以翻译后的选择器应该是
$('#myform input[name="violationCategory[1].subCategory"]').addClass('inputBoxError');
Update 更新资料
You need to select a <select>
element, then you need to change the element selector input
to select
like $('#' + formId + ' select[name="' + key + '"]').addClass('inputBoxError');
您需要选择一个
<select>
元素,然后需要更改元素选择器input
以进行select
例如$('#' + formId + ' select[name="' + key + '"]').addClass('inputBoxError');
Special characters need to be escaped by \\
. 特殊字符需要用
\\
进行转义。 Which needs to be escaped as well, so - here's an example to deal with your case: http://jsfiddle.net/tb2cW/1/ 同样需要逃避,所以-这是一个处理您的案例的示例: http : //jsfiddle.net/tb2cW/1/
And here's the list of characters in need of escaping: ~!@$%^&*()_+-=,./\\';:"?><[]{}|
and ` 以下是需要转义的字符列表:
~!@$%^&*()_+-=,./\\';:"?><[]{}|
和`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.