JQuery 附加到使用数组进行选择
很简单,但你猜怎么着,不适合我。我有一个像这样的逗号分隔列表: Option1,Option2,Option3 我想将其附加到 ;
我可以像这样“拆分”列表(在获取列表的函数内):
var optionsarray = $(this).val().split(',');
$(optionsarray).each(function(i){
var seloption = '<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>';
});
但是现在如何我是否将 seloption
添加到我的选择列表中?如果我将
$('#selecttoappendto').append('<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>');
或
$('#selecttoappendto').append(seloption);
放在每个循环内,则什么也不会发生。将其放在我可以附加的每个之外,例如 optionsarray[0]
或 optionsarray[1]
等,但我无法附加 optionsarray[i] 我以哪种方式(在每个内部或外部)执行此操作。请帮忙 - 提前致谢
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>';
});
But now how do I append seloption
to my select list. If I put
$('#selecttoappendto').append('<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>');
or
$('#selecttoappendto').append(seloption);
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从空字符串开始,您可以使用
+=
在循环中构建字符串。然后.append()
字符串。或者另一种选择是单独构建元素,将它们存储在容器中,然后从容器中附加它们。
修复了
children
之后缺少()
的问题。Starting with an empty string, you can build a string in the loop usingt
+=
. Then.append()
the string.or another option would be to build the elements separately, store them in a container, then append them from the container.
Fixed missing
()
afterchildren
.这是我编写和使用的内容;它比 user113716 给出的解决方案快一点,因为您跳过创建临时选择,所有这些都会附加到该临时选择(即使它是 DOM 片段,它仍然需要一些时间),并且您还跳过了 .children() 查找并在最后的附加部分展开。
所以:
我实际上正是为此编写了这些插件;通过这种方式,我在 250 毫秒内构建了 1500 多个选项选择。 :D
Here's what I wrote and use; it's a little faster than the solution user113716 gave, because you're skipping creating the temp select, all those appends to that temp select (even if it is a DOM fragment, it still takes some time), and you're also skipping the .children() find and unwrapping at the end for that final append.
So:
I actually wrote those plugins for exactly this; doing it this way, I build a 1500+ option select in under 250 ms. :D
jQuery 的
.append
现在可以接受数组(不知道它是什么)就像 2012 年一样),所以这也有效:$也可以使用.map
函数。它将创建一个具有.appendTo
的 jQuery 数组:jQuery's
.append
can take an array these days (dunno what it was like in 2012), so this works too:The
$.map
function can also be used. It will create a jQuery array that has an.appendTo
: