繁体   English   中英

如何选择名称数组中的所有元素?

[英]How to select all elements in name array?

我试图总结使用jQuery的无线电选择的集合。

<input name="cost[alpha]" type="radio" >
<input name="cost[beta]" type="radio">
<input name="cost[delta]" type="radio">
...
$('input[name="cost[*]"]').each( function() {
    ...
}

这不起作用,因为它尝试解析名称为“ cost [*]”的输入。 理想情况下,我想遍历cost数组中的任何元素。 有没有使用jQuery的首选方法? 我的表单中还有其他元素使用单选类型,因此通常选择单选不是一个有效的选择。

将属性选择器设为“以” 开头的选择器( ^= ):

$('input[name^="cost"]').each(function() {
    ...
});

如果您发现还有其他以“ cost”甚至“ cost [”开头的输入元素,那么您可能想考虑改变查询元素的方式。 一种替代方法是在要定位的元素上添加特殊的类名,然后完全忽略它们的名称。 例如:

<input name="cost[alpha]" type="radio" class="form-cost">
<input name="cost[beta]" type="radio" class="form-cost">
<input name="cost[delta]" type="radio" class="form-cost">

然后,您的选择器非常简单且非常有针对性:

$('input.form-cost').each(function() {
    ...
});

通过简单地将元素包装在具有唯一ID或类名的容器中,并查询其中包含的输入元素(如Allende在评论中建议的那样),可能会获得最佳性能:

<div id="cost-inputs">
    <input name="cost[alpha]" type="radio">
    <input name="cost[beta]" type="radio">
    <input name="cost[delta]" type="radio">
</div>

$('#cost-inputs input').each(function() {
    ...
});

尝试在jQuery中使用包含选择器

$("input[name*='cost[']").each(function(){});

尝试:

var sum = 0;
$("input[name^='cost']").each(function() {
     sum += Number($(this).val());
});

关于“以选择器开始”:[name ^ =“ value”]
https://api.jquery.com/attribute-starts-with-selector/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM