我有以下HTML:
<div id='show-label'>
<select id="comboboxShowLabel">
<option value="">Hide or show labels?</option>
<option value="Show Labels">Show Label</option>
<option value="Hide Labels">Hide Label</option>
</select>
</div>
我想在运行时将<select></select>
添加到父div,ala:
<div id='show-label'>
</div>
$("#show-label").html("<select id='comboboxShowLabel'>")
.append("<option value=''>Hide or show labels?</option>")
.append("<option value='Show Labels'>Show Label</option>")
.append("<option value='Hide Labels'>Hide Label</option>")
.append("</select>");
对于我不知道的原因,关闭标记不会被注入到页面中。
我已经尝试了上面的代码以及类似的东西:
.append("<option value='Hide Labels'>Hide Label</option></select>")
将这些元素"批处理"到单个.append中是否有一些排序要求?我想知道这种方法在加载到DOM中时是否看起来形式不太好,所以它被忽略了。。。
谢谢!
试试这个:
$("#show-label").append(function() {
return $("<select id='comboboxShowLabel'>")
.append("<option value=''>Hide or show labels?</option>")
.append("<option value='Show Labels'>Show Label</option>")
.append("<option value='Hide Labels'>Hide Label</option>");
});
append()
只将一个元素附加到另一个元素。您需要做的是生成一个有效的select标记。然后可以将选项附加到该选项上。请参阅文档。
$("#show-label").html("<select id='comboboxShowLabel'></select>")
$('#show-label select').append("<option value=''>Hide or show labels?</option>")
.append("<option value='Show Labels'>Show Label</option>")
.append("<option value='Hide Labels'>Hide Label</option>");
改为执行以下操作:
var $select = $("<select id='comboboxShowLabel'></select>");
$("#show-label").html($select);
$select.append("<option value=''>Hide or show labels?</option>")
.append("<option value='Show Labels'>Show Label</option>")
.append("<option value='Hide Labels'>Hide Label</option>");
如果出于任何原因需要在后面追加。否则,这样做可以提高浏览器效率(对实际dom进行一次更改,而不是多次更改):
var $select = $("<select id='comboboxShowLabel'></select>")
.append("<option value=''>Hide or show labels?</option>")
.append("<option value='Show Labels'>Show Label</option>")
.append("<option value='Hide Labels'>Hide Label</option>");
$("#show-label").html($select);
此行:
$("#show-label").html("<select id='comboboxShowLabel'>")
设置#show-label
的html,并返回表示#show-label
的jQuery对象。第二部分很重要,因为它意味着你的下一行,
.append("<option value=''>Hide or show labels?</option>")
也附加到#show-label
,这不是您想要的。试试这个:
$("#show-label").empty().append(
$('<select/>')
.append("<option value=''>Hide or show labels?</option>")
.append("<option value='Show Labels'>Show Label</option>")
.append("<option value='Hide Labels'>Hide Label</option>")
);
您可以简单地附加完成的选择,然后添加选项:
$("#show-label").html("<select id='comboboxShowLabel'></select");
$("#comboboxShowLabel")
.append("<option value=''>Hide or show labels?</option>")
.append("<option value='Show Labels'>Show Label</option>")
.append("<option value='Hide Labels'>Hide Label</option>");