繁体   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