【问题标题】: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】:
如果 <option> 不是 <select> 的子代,则 <option> 没有意义。首先创建<select>。
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>