我需要使用javascript在html中的选择标记中添加2015年到今年。我在下面有一个代码,但是它不显示或不返回期望值,并且select标记也为空。我该如何实现?
HTML:
<div class="cell colspan3">
<div class="input-control select full-size">
<h5>Year:</h5>
<select id="cboYear">
<option value="0" selected disabled hidden>Select Year</option>
</select>
</div>
</div>
JAVASCRIPT:
function Years() {
var today = new Date(),
yyyy = today.getFullYear()
for (var i = 0; i < 10; i++, yyyy++) {
for (var x = 1; x > i; x++) {
$('#cboYear').append('<option value ="' + x + '">' + yyyy + '</option>')
}
}
}
答案 0 :(得分:0)
假设您在Web应用程序中使用jquery
,我对您发布的代码进行了一些修改。这是附加年份2015
的代码,以使用javascript中的循环来呈现。
<script type="text/javascript">
$(document).ready(function(){
Years(); // this will run the function Years() after the DOM (document object model) has been loaded.
});
function Years() {
// get the current date and put in today variable
var today = new Date();
// get the year and put it in yyyy variable
yyyy = today.getFullYear();
// appending from year 2015 up to present in the select tag
for (var index = 2015; index <= yyyy; index++) {
$('#cboYear').append('<option value ="' + index + '">' + index + '</option>')
}
}
</script>
答案 1 :(得分:0)
<select>
标签的引用| .querySelector(selector);
<option>
标签| .createElement("option");
option.text
属性option.value
属性<option>
添加到<select>
| select.add(option)
方法for
循环
function setOpt(selector, text, value) {
var node = document.querySelector(selector);
var opt = document.createElement("option");
opt.text = text;
opt.value = value;
node.add(opt);
return false;
}
function T(t) {
var now = new Date();
var time;
switch (t.toLowerCase()) {
case 'm':
time = now.getMonth() + 1;
break;
case 'd':
time = now.getDate();
break;
case 'y':
time = now.getFullYear();
break;
default:
break;
}
return time;
}
for (let i = 2015; i <= T('y'); i++) {
setOpt('#cboYear', i, i);
}
<div class="cell colspan3">
<div class="input-control select full-size">
<h5>Year:</h5>
<select id="cboYear">
<option value="0" selected disabled hidden>Select Year</option>
</select>
</div>
</div>
答案 2 :(得分:0)
希望对您有帮助
HTML
<div class="cell colspan3">
<div class="input-control select full-size">
<h5>Year:</h5>
<select id="cboYear"></select>
</div>
</div>
脚本代码
function Years() {
var today = new Date();
var yyyy = today.getFullYear();
var content = '<option value="-1">Select Year</option>';
for (var x = 1; x <= 10; x++, yyyy++) {
content += '<option value="' + x + '">' + yyyy + '</option>';
}
$('#cboYear').append(content);
}
别忘了添加jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>