使用jQuery使用数组填充下拉选择 [英] Populate dropdown select with array using jQuery

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

问题描述

我正在尝试使用jQuery使用数组填充下拉选择.

I am trying to populate a dropdown select with an array using jQuery.

这是我的代码:

        // Add the list of numbers to the drop down here
        var numbers[] = { 1, 2, 3, 4, 5};
        $.each(numbers, function(val, text) {
            $('#items').append(
                $('<option></option>').val(val).html(text)
            );            
        // END

但是我遇到了一个错误.每个功能都是我从这个网站上获得的.

But I'm getting an error. The each function is something I am got off this website.

是否由于使用一维数组而被炸毁?我希望选项和文本都相同.

Is it bombing out because I'm using a one-dimensional array? I want both the option and the text to be the same.

推荐答案

尝试循环:

var numbers = [1, 2, 3, 4, 5];

for (var i=0;i<numbers.length;i++){
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}


更好的方法:


Much better approach:

var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
   option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);

这篇关于使用jQuery使用数组填充下拉选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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