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

Ben*_*ell 0 javascript jquery jquery-selectors

我试图用jQuery总结一组无线电选择.

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

这不起作用,因为它尝试解析名为"cost [*]"的输入.理想情况下,我想迭代成本数组中的任何元素.有没有一种首选的方法来使用jQuery?我的表单中有其他元素使用无线电类型,因此选择无线电通常不是一个有效的选项.

Cᴏʀ*_*ᴏʀʏ 6

使属性选择器" 开始于 "选择器(^=):

$('input[name^="cost"]').each(function() {
    ...
});
Run Code Online (Sandbox Code Playgroud)

如果您发现其他输入元素以"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">
Run Code Online (Sandbox Code Playgroud)

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

$('input.form-cost').each(function() {
    ...
});
Run Code Online (Sandbox Code Playgroud)

您可以通过简单地将元素包装在具有唯一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() {
    ...
});
Run Code Online (Sandbox Code Playgroud)