选项标签中的选定属性

时间:2017-10-26 06:24:05

标签: javascript

我有一个通过循环填充的下拉列表。当<%if o.getNextPage()%>等于i时,应添加所选属性。

&#13;
&#13;
<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();
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您可以将value属性添加到option代码。

正如@ 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);
}

答案 1 :(得分:0)

这是生成下拉列表并保持性能的正确方法,因为documentFragment

只需与DOM交互一次

&#13;
&#13;
// 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);
&#13;
<select id="dropDown" onchange="display(this.value)"></select>
&#13;
&#13;
&#13;

我省略了display函数,因为它引用了未提供的代码,因此无关紧要。