答案 0 :(得分:4)
$(document).ready(function() {
// Display DOM to a specific id (div#log)
$("#log").html("<select class='form-control selcls' id='meterOption'>");
var meterNum = 1;
for (var i = 1; i <= 12; i++) {
$("#meterOption").append("<option value=" + meterNum + ">" + meterNum + "</option>");
meterNum++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="log"></div>
答案 1 :(得分:3)
$(document).ready(function() {
// Display DOM to a specific id (div#log)
$("#log").html("<select class='form-control selcls' id='meterOption'></select>");
var meterNum = 1;
for (var i = 1; i <= 12; i++) {
$("#log > select").append("<option value=" + meterNum + ">" + meterNum + "</option>");
meterNum++;
}
// $("#log").append("</select>");
});
.selcls {
padding: 9px;
border: solid 1px #517B97;
outline: 0;
background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #CAD9E3), to(#FFFFFF));
background: -moz-linear-gradient(top, #FFFFFF, #CAD9E3 1px, #FFFFFF 25px);
box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
-moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
-webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="log">
</div>
不是$("#log")
,$("#log > select")
。
如果您想在select
追加,则必须找到select
代码。
但是,您找到了$("#log")
,它不是select
标记。
所以,你应该写${"#log > select")
答案 2 :(得分:1)
你想要的是:
$("#log").html("<select class='form-control selcls' id='meterOption'>");
#log becomes <select...>
#log.append("x1")
#log becomes <select...>x1
#log.append("x2")
#log becomes <select...>x1x2
#log.append("</select>")
#log becomes <select...>x1x2</select>
你得到的是JQuery正在&#34;乐于助人&#34;并为您关闭初始选择。如果你知道它正在发生,那也不是坏事。
$("#log").html("<select class='form-control selcls' id='meterOption'>");
#log becomes <select...></select>
#log.append("x1")
#log becomes <select...></select>x1
#log.append("x2")
#log becomes <select...></select>x1x2
#log.append("</select>")
#log stays <select...></select>x1x2
您将选项添加到div,而不是选择。
$("#meterOption").append("<option value=" + meterNum + ">" + meterNum + "</option>");
会将项目添加到选择框中。
不需要添加结束/选择。