【问题标题】:how to use append() after() before() when adding parent tag添加父标签时如何使用append() after() before()
【发布时间】:2022-01-19 06:13:43
【问题描述】:

我为#inputPanel添加了多个<option>,然后尝试设置<select>

for (i = 0 ;i < data.length;i++){
    $('#inputPanel').append(`<option>${data[i]['name']}</option>`);
}

$('#inputPanel').after("</select>");
$('#inputPanel').before("<select>");
console.log($('#inputPanel').html()); // there is not select???

select 标签未添加到DOM

我怎样才能做到这一点??

【问题讨论】:

    标签: javascript html jquery


    【解决方案1】:

    如果 &lt;option&gt; 不是 &lt;select&gt; 的子代,则 &lt;option&gt; 没有意义。首先创建&lt;select&gt;

    const data = [{ name: 'a' }, { name: 'b' }];
    const select = $('<select>').appendTo('#inputPanel');
    for (const { name } of data) {
      $('<option>')
        .text(name) // .text is safer than direct interpolation
        .appendTo(select);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="inputPanel"></div>

    【讨论】:

    • 谢谢,这看起来非常整洁和酷。效果很好
    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多