【问题标题】:JQuery iterate through JSON array and insert into dynamic HTML SELECTJQuery 遍历 JSON 数组并插入动态 HTML SELECT
【发布时间】:2015-11-02 04:22:30
【问题描述】:

对于我的一生,我不知道为什么这不起作用 - 我尝试了多种方法来尝试将 JSON 数据插入到 <option> 代码中,每次它不起作用 - 它仅输出 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 函数之后,但这也不起作用。

【问题讨论】:

    标签: jquery arrays forms select


    【解决方案1】:

    在使用.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);
    })
    

    【讨论】:

    • 效果很好,是我唯一没有想过尝试的事情(而且真的应该尝试!)。其他项目将需要此功能,因此一次性解决了多个问题。非常感谢!
    • @Hyperjase 很高兴为您提供帮助! :)
    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多