使用jquery append将选项值添加到select元素中不起作用 [英] Using jquery append to add option values into a select element not working

查看:1195
本文介绍了使用jquery append将选项值添加到select元素中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望动态填充一个select元素,其中包含存储在数组中的项的名称。



由于某种原因,它不起作用,我不知道为什么。



HTML:

 < div class =col-md-4 col-md-offset-4> 
< select class =select1>
< / select>

< select class =select2>
< / select>
< / div>

请注意,我正在使用bootstrap进行布局。



这是我用来尝试填充.select1的jquery



JQUERY:

  select:function(){
$ .each(state.greens,function(index,value){
$(。 select1)。append(< option value ='+ index +'>+ state.greens [index] .name +< / option>);
});
}

请注意,'select'函数存储在名为'display'的对象中。



state.greens是我试图访问的数组的名称。



所以在我的html页面的末尾,我调用display.select();调用该函数。



控制台中没有显示错误消息。



另外,我看到了这个问题:附加使用jQuery选择的选项不起作用



但是正在寻找一个以jquery为中心的答案,这似乎应该是你可以这样做:

  $。each(state.greens,function(index,value){
$('。select1')。append($('< option>',{
值:index,
text:state.greens [index] .name
}));
});


I'm looking to dynamically populate a select element with names of items that are stored into an array.

For some reason it's not working and I'm not sure why.

HTML:

<div class="col-md-4 col-md-offset-4">
    <select class="select1">
    </select>
        and
    <select class="select2">
    </select>
</div>

Note that I'm using bootstrap for layout.

Here's the jquery I'm using to try and populate ".select1"

JQUERY:

select: function() {
    $.each(state.greens, function(index, value) {
        $(".select1").append("<option value =' " + index + " '>" + state.greens[index].name + "</option>");
    });
}

Note that the function 'select' is stored within an object called 'display'.

state.greens is the name of the array I'm trying to access.

So at the end of my html page I call display.select(); to call the function.

No error messages are showing up in the console.

Also, I saw this question: Appending options to select using jQuery doesn't work

but was looking for a jquery centric answer and this seems like it ought to work.

解决方案

You can do in that way:

$.each(state.greens, function(index, value) {
    $('.select1').append($('<option>', {
        value: index ,
        text: state.greens[index].name
    }));
});

这篇关于使用jquery append将选项值添加到select元素中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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