简体   繁体   English

使用jQuery追加将选项值添加到选择元素不起作用

[英]Using jquery append to add option values into a select element not working

I'm looking to dynamically populate a select element with names of items that are stored into an array. 我正在寻找使用存储在数组中的项目名称动态填充select元素。

For some reason it's not working and I'm not sure why. 由于某种原因,它无法正常工作,我不确定为什么。

HTML: 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" 这是我用来尝试填充“ .select1”的jQuery

JQUERY: 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. state.greens是我尝试访问的数组的名称。

So at the end of my html page I call display.select(); 因此,在我的html页面末尾,我调用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 另外,我看到了这个问题: 使用jQuery选择附加选项不起作用

but was looking for a jquery centric answer and this seems like it ought to work. 但是正在寻找以jquery为中心的答案,这似乎应该可行。

You can do in that way: 您可以通过以下方式进行操作:

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

When you append you are basically adding to the .innerHTML value of a container. 追加时,基本上是在添加容器的.innerHTML值。 This works for most elements except for <select> . 这适用于除<select>之外的大多数元素。 You'll have to add elements properly for the DOM to pick it up: 您必须正确添加元素以使DOM能够使用它:

var select=document.getElementById('select1');
var option=document.createElement('option');
option.setAttribute('value','option1');
option.innerHTML='Option 1';
select.appendChild(option);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM