JQuery迭代JSON数组并插入动态HTML SELECT

时间:2015-08-10 09:48:38

标签: jquery arrays forms select

对于我的生活,我不知道为什么这不起作用 - 我已经尝试了多种尝试将JSON数据插入到<option>代码中的方法,而不是每次#&# 39; t就是这样 - 它只是输出HTML文本而不是<select>下拉列表

$.getJSON( "group.asp", function( data ) {
    $('#msgBox').html($('#msgBox').html() + '<div class="table-row"><div class="table-col-l">Name:</div><div class="table-col-r"><select id="name1"><option>SELECT</option>')
    $(data).each(function(index, element) {
        console.log(element)
        $('#msgBox').html($('#msgBox').html() + '<option>'+element.name+'</option>');
    });
    $('#msgBox').html($('#msgBox').html() + '</select></div></div>')
})

我尝试将其创建为一个单独的变量,该变量在.each函数之后插入但不起作用。

1 个答案:

答案 0 :(得分:3)

在使用.html()

之前尝试进行正确的字符串连接
$.getJSON( "group.asp", function( data ) {
    var str = $('#msgBox').html();
    str += '<div class="table-row"><div class="table-col-l">Name:</div><div class="table-col-r"><select id="name1"><option>SELECT</option>';
    $(data).each(function(index, element) {
        str += '<option>'+element.name+'</option>';
    });
    str += '</select></div></div>';
    $('#msgBox').html(str);
})
相关问题