我有多个选择元素。我目前从select元素中获取值,然后将一个字符串放在一起并通过ajax发送它们。有没有办法我可以循环选择元素然后分配值。我试过但无济于事。
DEMO http://jsfiddle.net/2Nxxp/1/
// current way
var opt1 = $('select[name="opt1"]').val();
var newOpt = $('select[name="newOpt"]').val();
var anotherOpt = $('select[name="anotherOpt"]').val();
var randomOpt = $('select[name="randomOpt"]').val();
var opt = $('select[name="opt"]').val();
var newOpt1 = $('select[name="newOpt1"]').val();
var 1newOpt = $('select[name="1newOpt"]').val();
// new way but not working
$.each([ 'opt1', 'newOpt', 'anotherOpt', 'randomOpt', 'opt', 'newOpt1', '1newOpt'], function( index, value ) {
var ''+value+'' = $('select[name="'+value+'"]').val();
});
QueryString = '&opt1='+opt1+'&newOpt='+newOpt+'&anotherOpt='+anotherOpt+'&randomOpt='+randomOpt+'&opt='+opt+'&newOpt1='+newOpt1+'&1newOpt='+1newOpt;
答案 0 :(得分:1)
只需使用jQuery serialize()方法:
QueryString = $('select').serialize();
答案 1 :(得分:0)
您可以创建一个将存储该值的对象。然后你的“新方式”将起作用:
var obj = {};
$.each([ 'opt1', 'newOpt', 'anotherOpt', 'randomOpt', 'opt', 'newOpt1', '1newOpt'], function( index, value ) {
obj[value] = $('select[name="'+value+'"]').val();
});
QueryString = '&opt1='+obj.opt1+'&newOpt='+obj.newOpt+'&anotherOpt='+obj.anotherOpt+'&randomOpt='+obj.randomOpt+'&opt='+obj.opt+'&newOpt1='+obj.newOpt1+'&1newOpt='+obj.1newOpt;
答案 2 :(得分:0)
var query = '';
$('select').each(function(){
query+= '&' + this.name + '=' + this.value;
});
或
var query = {};
$('select').each(function(){
query[this.name] = this.value;
});
答案 3 :(得分:0)
jQuery已经有一个函数可以从一组选定的表单元素.serialize()
创建一个查询字符串。你可以这样做:
QueryString = $('select[name="opt1"],select[name="newOpt"],select[name="anotherOpt"],select[name="randomOpt"],select[name="opt"],select[name="newOpt1"],select[name="1newOpt"]').serialize();
或者,如果您的页面上的<select>
元素的全部,请将其简化为:
QueryString = $('select').serialize();