2013-05-31 35 views
1

我知道關於這個問題已經有很多關於SO的帖子。但他們都不適合我的情況。jQuery - 獲取名稱屬性中方括號的錯誤

我受夠了如下命名格式,多重選擇輸入:

select name="violationCategory[${theCount.count-1}].subCategory" 

它轉換爲是這樣的:

select name="violationCategory[0].subCategory" 
select name="violationCategory[1].subCategory" 
.. so on 

我已經對這些選擇輸入,如果一些應用特定類條件得到滿足。 所以,我嘗試用一​​些替代方括號中是這樣的:

if(key.indexOf("[") >= 0){ 
     key = $.trim(key).replace("name=^[","name=^\\["); 
     key = $.trim(key).replace("].","\\]."); 
     alert(key); 
     $("#" + formId + " select[name=" + key + "]").addClass('inputBoxError');        
    } 

警報打印:

violationCategory[1\].subCategory] 

,我得到的錯誤:

Uncaught Error: Syntax error, unrecognized expression: #referralViolationForm select[name=violationCategory[1\].subCategory] 

當我更改代碼到:

key = $.trim(key).replace("].","\]."); 

個警報打印:

violationCategory[1].subCategory] 

,我得到的錯誤:

Uncaught Error: Syntax error, unrecognized expression: #referralViolationForm select[name=violationCategory[1].subCategory] 

所以,基本上它的工作原理沒有辦法。

任何人都可以幫我解決如何擺脫方括號。

回答

4

你的屬性值應在""包裹,沒有必要躲避[]

$('#' + formId + ' input[name="' + key + '"]').addClass('inputBoxError'); 

所以翻譯的選擇應該是

​​

更新
您需要選擇一個<select>元素,那麼您需要將元素選擇器input更改爲select ike $('#' + formId + ' select[name="' + key + '"]').addClass('inputBoxError');

+1

+1雖然,但我想OP在說話關於選擇輸入,所以'select [name =「violationCategory [1] .subCategory」]''? – PSL

+0

感謝您的意見。改變單引號的位置對我有效:$(「#」+ formId +「select [name ='」+ key +「']」)。addClass('inputBoxError'); – tarares

+0

@PSL我的壞!我相應地更新了我的問題和答案! – tarares