javascript 如何从多维数组填充列表框(组合框)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10267982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:14:26  来源:igfitidea点击:

How to Populate a List Box (combo box) from a Multi-Dimensional Array?

javascriptarrays

提问by kentrenholm

I'm a student in JavaScript and we have an assignment due tonight. I've been working, and re-working, the code for bit.

我是 JavaScript 的学生,今晚我们有一个作业要交。我一直在工作,并重新编写代码。

Essentially, I'm struggling with populating a List Box (combo box) from a Multi-Dimensional Array.

本质上,我正在努力从多维数组填充列表框(组合框)。

I have a multi-dimensional array created and it works (I sent my results to an alert box).

我创建了一个多维数组并且它可以工作(我将结果发送到警报框)。

var concertArray = [
        ["Billy Joel", "99", "equal.png"],
        ["Bryan Adams", "89", "higher.png"],
        ["Brian Adams", "25", "lower.png"]

        ];

But, I have no idea how to populate this array to a select list box (combo box).

但是,我不知道如何将此数组填充到选择列表框(组合框)。

Any help, much appreciated.

任何帮助,非常感谢。

回答by Yogesh Prajapati

Use this Code.

使用此代码。

<html>

    <head>
     <script type="text/javascript">
        var concertArray = [
            ["Billy Joel", "99", "equal.png"],
            ["Bryan Adams", "89", "higher.png"],
            ["Brian Adams", "25", "lower.png"]
            ];

            function populate(){

                for(i=0;i<concertArray.length;i++){
                    var select = document.getElementById("test");
                    select.options[select.options.length] = new Option(concertArray[i][0], concertArray[i][1]);
                }

            }
        </script>
        </head>

    <body onload="populate();">
        <select id="test">
        </select>
    </body>     
</html>

this will help you.....

这会帮助你......

回答by gopi1410

extract the data which you want to add in combo box from the array, then use jquery appendto add them to the select tag.

从数组中提取要添加到组合框中的数据,然后使用jquery append将它们添加到选择标签中。

<select id="test">
</select>

Iterate through the array & store the data to be added in a variable, say var data, then:

遍历数组并将要添加的数据存储在变量中,比如 var data,然后:

$('#test').append('<option value="'+data+'">'+data+'</option');