[英]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.