我想在选项选择框的末尾追加新的价值。数量应该继续,而不是从1开始。
var n_standard = 1;
function removeStandard() {
var select = document.getElementById('selectBoxStandard');
for (var i = Number($("#selectBoxStandard").val()); i <= n_standard; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
<label for="rooms" style="color:black">No. of rooms: </label>
<select required tabindex="10" id="selectBoxStandard" name="n_rooms">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
这段JavaScript代码将填补基于n_standard的值期权的价值就应该继续,而不是从1重新开始编号。
程序输出
option
0
1
2
3
4
5
6
1
预计输出
option
0
1
2
3
4
5
6
7
8
您可以查询option
目前有多少select
s拥有并补充说,作为补偿:
var offset = select.find("option").length;
opt.value = i + offset;
var n_standard = 1;
function removeStandard() {
var select = $('#selectBoxStandard');
var offset = select.find("option").length;
// not clear why you would start at 5 and check 5<=1 which will always give nothing
// so for demo, always adds one item (so doesn't need the loop)
// change n_standard to add more than one at a time
//for (var i = Number(select.val()); i <= n_standard; i++) {
for (var i = 0; i < n_standard; ++i) {
var opt = document.createElement('option');
opt.value = i + offset;
opt.innerHTML = i + offset;
select.get(0).appendChild(opt);
}
}
$("#b").click(removeStandard);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="rooms" style="color:black">No. of rooms: </label>
<select required tabindex="10" id="selectBoxStandard" name="n_rooms">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<button id='b'>click me</button>
或者,你可以在开始值设置为最高值,如果可能有差距。
使用select.length
在代码中得到<option>
<select>
的数量。 https://www.w3schools.com/jsref/prop_select_length.asp
var n_standard = 1;
function removeStandard(){
var select = document.getElementById('selectBoxStandard');
for (var i = Number($("#selectBoxStandard").val()); i< n_standard; i++){
var opt = document.createElement('option');
opt.value = select.length;
opt.innerHTML = select.length;
select.appendChild(opt);
}
}
removeStandard();
目前还不清楚是什么你正在尝试做的。但是,如果你试图通过增加选项循环试试这个:
var n_standard = 9;
var select = document.getElementById('selectBoxStandard');
for (var i = Number(select.value); i <= n_standard; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);}
与增加值基于n_standar这将动态添加的选项。