[英]Create JS array from input field values
我有x個輸入字段,其中class ='agency_field'。 如何創建一個包含此類所有字段值的JS數組?
使用jQuery,這會產生語法錯誤:
$(“。agency_field”)。each(function(index){agencies [] = $(this).val();});
您可以使用.map
,這可能更適合您的目的:
var values = $(".agency_field").map(function() {
return this.value;
}).get();
alert(values.join(","));
var agencies = [];
$(".agency_field").each(function(index) { agencies.push($(this).val()); });
您正在為每次迭代創建一個新數組。 嘗試在每次調用之前實例化一個數組,並在每次迭代時添加到數組中。
var arr = []; $(".agency_field").each(function(index) { arr.push($(this).val()); });
arr
最終會包含你想要的東西。
您的代碼應稍微更改為:
var agencies = [];
$(".agency_field").each(function(index) {
agencies.push($(this).val());
});
您需要先創建一個數組,然后將每個值添加到該數組:
var agencies = [];
$(".agency_field").each(function(index) { agencies.push($(this).val()) });
你已經習慣了像php這樣的語言? ;)在Javascript中,您將使用array.push()附加到數組; 所以
$(".agency_field").each(function(index) { agencies.push( $(this).val() ); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.