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

How to select all elements in name array?

本文关键字:数组 元素 何选择 选择      更新时间:2023-09-26

我正在尝试使用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[*]"的输入。理想情况下,我想迭代成本数组中的任何元素。用jQuery做这件事有什么更好的方法吗?我的表单中还有其他使用radio类型的元素,因此选择radio通常不是一个有效的选项。

使属性选择器为"以"开头的"选择器(^=):

$('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() {
    ...
});

Try with contains selector in jquery

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

尝试:

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

关于" started With Selector": [name^="value"]
https://api.jquery.com/attribute-starts-with-selector/