簡體   English   中英

使用'name'屬性標簽的多個select2元素的jQuery選擇器

[英]jQuery selector for multiple select2 element using 'name' attribute tag

我試圖在各種輸入上輸出驗證錯誤並選擇表單上的元素。 但是我似乎無法使用類/屬性選擇器來獲取元素。 我使用引導程序的form-contorl類來標識所有輸入,並使用select2插件來修復選擇框。

這對於標准輸入框和選擇框可以很好地工作,但是對於多個選擇框(在name屬性的末尾需要“ []”),它將失敗並返回一個空的jquery對象。

編輯:順便說一句, eKey返回不帶[] genres

的HTML

<select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true">
    <option value="1">RPG</option>
    <option value="2">FPS</option>
    <option value="3">MMO</option>
</select>

JS

$.each(errors, function (eKey, messages){

    var $input = $('.form-control[name=' + eKey + ']');
    //do stuff with error messages (bootstrap popovers)
});

有什么想法可以通過jquery選擇器選擇輸入元素嗎?

您可以使用以選擇器開頭的屬性

 var eKey = "genres"; var $input = $('.form-control[name^=' + eKey + ']'); console.log($input[0].name); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true"> <option value="1">RPG</option> <option value="2">FPS</option> <option value="3">MMO</option> </select> 

或轉義選擇器字符串

 var eKey = "genres\\\\[\\\\]"; var $input = $('.form-control[name=' + eKey + ']'); console.log($input[0].name); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true"> <option value="1">RPG</option> <option value="2">FPS</option> <option value="3">MMO</option> </select> 

jQuery版本3+

 var eKey = $.escapeSelector("genres[]"); var $input = $('.form-control[name=' + eKey + ']'); console.log($input[0].name); 
 <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true"> <option value="1">RPG</option> <option value="2">FPS</option> <option value="3">MMO</option> </select> 

另請參見為什么jQuery 3無法在屬性選擇器中識別'#'字符?

您可以嘗試在屬性值中使用不同的搜索算法,例如,屬性以選擇器開頭- $(".form-control[name^='genres']")

完整說明https://api.jquery.com/category/selectors/attribute-selectors/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM