[英]Selected attribute in option tag
I have a dropdown that's populated through a loop.我有一个通过循环填充的下拉列表。 The selected attribute should be added when <%if o.getNextPage()%>
is equal to i
.当<%if o.getNextPage()%>
等于i
时,应添加 selected 属性。
<select id="dropDown" onchange="display(this.value)"> var start = 1; var end = noOfPages; var options = ""; for (var i = start; i <= end; i++) { options += "<option>" + i + "</option>"; } document.getElementById("dropDown").innerHTML = options; function display(e) { document.getElementById("hidden").value = e; document.invoiceForm.submit(); }
You can add value
attribute to the option
tag.您可以将value
属性添加到option
标签。
As suggested by @3Dos in comments you can use 'document.createElement' without needing to insert raw HTML like this:正如@3Dos 在评论中所建议的,您可以使用 'document.createElement' 而无需像这样插入原始 HTML:
var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
document.getElementById('dropDown').appendChild(opt);
}
This is the proper way of generating your dropdown list and preserve performance as you interact with the DOM only once thanks to the documentFragment由于documentFragment,这是生成下拉列表并保持性能的正确方法,因为您只与 DOM 交互一次
// These were not provided by OP but added to actually get this snippet running var noOfPages = 5; var start = 1; var end = noOfPages; var options = document.createDocumentFragment(); for (var i = start; i <= end; i++) { var option = document.createElement('option'); option.value = i; option.textContent = i; options.appendChild(option); } document.getElementById("dropDown").appendChild(options);
<select id="dropDown" onchange="display(this.value)"></select>
I omitted the display
function which is irrelevant as it refers to unprovided code.我省略了无关的display
功能,因为它指的是未提供的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.