简体   繁体   English

如何通过JavaScript选择选择标签的选项?

[英]How to select option of select tag via JavaScript?

Below javascript to populate years, now need to select year that is posted from frontend. 在javascript下面,以填充年份,现在需要选择从前端发布的年份。

eg if year 1903 is sent the option with value 1903 should be selected. 例如,如果发送1903年,则应选择值为1903的选项。

var start = 1900;
var end = new Date().getFullYear();
var options = "";
var yearpost = "<?php echo $year ?>";
for (var year = start; year <= end; year++) {
  options += "<option "
  if (year == yearpost) {
    document.write('selected')
  }
  ">" + year + "</option>";
}
document.getElementById("year").innerHTML = options;

You wrongly wote document.write instead of options += inside if block : 您错误地将document.write替换为if块,而不是options +=

 var start = 1900; var end = new Date().getFullYear(); var options = ""; var yearpost = "2011"; for (var year = start; year <= end; year++) { options += "<option "; if (year == parseInt(yearpost)) { options += ('selected') } options += ">" + year + "</option>"; } document.getElementById("year").innerHTML = options; 
 <select id="year"></select> 

Or you can simplify the if statement to this: 或者,您可以将if语句简化为:
options += '<option ' + (year == parseInt(yearpost) ? ' selected' : '') + '>' + year + '</option>';

If I understood correctly you want the option to be selected when it matches the year. 如果我理解正确,则希望在与年份匹配时选择该选项。 The way you're doing it you are writing to the document, instead you should add it to the string you're creating. 执行此操作的方式是将其写入文档,而应将其添加到正在创建的字符串中。 Inside your if statement try doing this instead : option += "selected" 在您的if语句中,尝试改为执行以下操作: option += "selected"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM