将选择列表与数组中的项追加

时间:2018-12-20 15:06:54

标签: javascript jquery arrays select

在选择下拉菜单中有一个我想用作选项的数组。当我运行代码时,它仅附加该数组的第一项,我不确定为什么。

 $.ajax({
            type: 'post',
            url: 'Reporting.aspx/actionType',
            contentType: 'application/json; charset=utf-8',
            data: '{ reportType: "' + reportType + '" }',
            dataType: 'json',
            success: function (r, re) {
                $.each(r, function () {
                    testList.push(r.d)
                })

                for (var i = 0; i < testList.length; i++) {

                    $('#drpAction').append('<option>' + testList[0][i] + '</option>')

                }

                console.log(testList)
            },
            failure: function () {
                swal({
                    title: 'Error',
                    text: 'There was an error loading the data',
                    confirmButtonText: 'OK'
                })
            }
        })

3 个答案:

答案 0 :(得分:1)

您正在遍历testList.length,但使用testList[0][i] ..尝试使用testList[i],就像我在这里所做的那样:

for (var i = 0; i < testList.length; i++) {
    $('#drpAction').append('<option>' + testList[i] + '</option>')
}

但是,如果要显示的项目位于testList[0]内部,则您也可以遍历testList[0].length而不是testList.length,例如:

for (var i = 0; i < testList[0].length; i++) {
    $('#drpAction').append('<option>' + testList[0][i] + '</option>')
}

如果此操作无济于事,我必须看看您的testList是什么样。

答案 1 :(得分:1)

我相信您必须遍历testList[0]

中的项目

var testList = [[1,2,3]]

for (var i = 0; i < testList[0].length; i++) {
  $('#drpAction').append('<option>' + testList[0][i] + '</option>')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="drpAction"></select>

答案 2 :(得分:0)

这是您的问题testList[0][i],您正在针对testList进行循环,但是您想访问testList[0]内的列表

您应该将i放在第一个括号之间

$('#drpAction').append('<option>' + testList[i] + '</option>')

或检查testList[0].length