JQuery追加以选择数组 [英] JQuery append to select with an array

查看:15
本文介绍了JQuery追加以选择数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单,但你猜怎么着,不适合我.我有一个像这样的逗号分隔列表: Option1,Option2,Option3 我想附加到 <select> 所以它变成 <select><option>Option1</option><option>Option2</option><option>Option3</option></select>

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);

在每个循环内什么都没有发生.把它放在我可以附加的每个之外代码>我做的任何方式(在每个内部或外部).请帮忙 - 在此先感谢

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

推荐答案

从一个空字符串开始,你可以使用+=在循环中构建一个字符串.然后 .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');

<小时>

修复了 children 之后缺少的 ().


Fixed missing () after children.

这篇关于JQuery追加以选择数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆