JQuery的追加一个数组来选择 [英] JQuery append to select with an array
问题描述
很简单,但你猜怎么着,不适合我。我有一个逗号分隔的列表如下:选项1,选项2,选项3,我要追加到<选择>
因此它成为<$c$c><select><option>Option1</option><option>Option2</option><option>Option3</option></select>$c$c>
very simple but guess what, not for me. I have a comma separated list like this: Option1,Option2,Option3 that I want to append to a <select>
so it becomes <select><option>Option1</option><option>Option2</option><option>Option3</option></select>
我可以分裂列表这样的(即获取列表中的一个函数里):
I can "split" the list like this (inside a function that gets the list):
var optionsarray = $(this).val().split(',');
$(optionsarray).each(function(i){
var seloption = '<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>';
});
但现在我怎么 seloption
添加到我的选择列表中。如果我把
But now how do I append seloption
to my select list. If I put
$('#selecttoappendto').append('<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>');
或
$('#selecttoappendto').append(seloption);
里面的每个循环什么也没有发生。把它外面的每一个我可以附加说 optionsarray [0]
或 optionsarray [1]
等等,但我不能获得追加 optionsarray [I]
这曾经办法,我这样做(内部或外部的每个)。请帮助 - 在此先感谢
inside the each loop nothing happens. Take it outside the each I can append say optionsarray[0]
, or optionsarray[1]
etc. but I cannot get to append optionsarray[i]
which ever way I do it (inside or outside the each). Help please - thanks in advance
推荐答案
为空字符串开始,你可以建立在循环字符串usingt + =
。然后 .append()
字符串。
Starting with an empty string, you can build a string in the loop usingt +=
. Then .append()
the string.
var optionsarray = $(this).val().split(',');
var seloption = "";
$.each(optionsarray,function(i){
seloption += '<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>';
});
$('#selecttoappendto').append(seloption);
或另一个选择是将分别建立的元素,其存储在一个容器中,然后从容器中附加这些
or another option would be to build the elements separately, store them in a container, then append them from the container.
var optionsarray = $(this).val().split(',');
var temp_sel = $('<select>');
$.each(optionsarray,function(i){
temp_sel.append('<option>',{text:optionsarray[i],
value:optionsarray[i]
});
});
temp_sel.children().appendTo('#selecttoappendto');
的固定失踪()
在孩子
。的
这篇关于JQuery的追加一个数组来选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!