简体   繁体   English

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

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

I am trying to sum a collection of radio selections using jQuery. 我试图总结使用jQuery的无线电选择的集合。

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

This does not function as it tries to resolve an input with the name "cost[*]". 这不起作用,因为它尝试解析名称为“ cost [*]”的输入。 Ideally I would like to iterate over any element in the cost array. 理想情况下,我想遍历cost数组中的任何元素。 Is there a preferred way of doing this with jQuery? 有没有使用jQuery的首选方法? I have other elements in my form that use the radio type so selecting radios in general is not a valid option. 我的表单中还有其他元素使用单选类型,因此通常选择单选不是一个有效的选择。

Make the attribute selector the " starts with " selector ( ^= ): 将属性选择器设为“以” 开头的选择器( ^= ):

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

If you find that you have other input elements that start with "cost" or even "cost[", then perhaps you want to think about changing the way you're querying for the elements. 如果您发现还有其他以“ cost”甚至“ cost [”开头的输入元素,那么您可能想考虑改变查询元素的方式。 One alternative would be adding a special class name to the elements you're targeting and forget about their names altogether. 一种替代方法是在要定位的元素上添加特殊的类名,然后完全忽略它们的名称。 For example: 例如:

<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">

And then your selector is very simple and very targeted: 然后,您的选择器非常简单且非常有针对性:

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

You might get the best performance out of simply wrapping the elements in a container with a unique id or class name, and querying for input elements that it contains (as suggested by Allende in the comments): 通过简单地将元素包装在具有唯一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(){});

Try: 尝试:

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

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

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

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