jQuery和连接多个字段值

时间:2011-04-05 17:12:47

标签: jquery

我怎样才能使这更简单?:

var address = jQuery.trim($("#Address1").val()) + " " + jQuery.trim($("#City").val()) + " " + jQuery.trim($("#State").val()) + " " + jQuery.trim($("#Zip").val());

2 个答案:

答案 0 :(得分:3)

试试这个:

var address = "";
$("#Address1, #City, #State, #Zip").each(function(){
    address += $.trim($(this).val()) + " ";
});

如果您正在寻找表单文本输入,那么您可以使其更简单,如下所示:

var address = "";
$(":text").each(function(){
    address += $.trim($(this).val()) + " ";
});

答案 1 :(得分:1)

在数组和循环中堆叠项目:

var arr = ['Address1', 'City', 'State', 'Zip'];
for(var i=0;i<arr.length;i++){
    arr[i] = $('#'+arr[i]).val();
}
var address = arr.join(' ');