原生jQuery實現隻顯示年份下拉框

本文實例為大傢分享瞭jQuery實現隻顯示年份下拉框的具體代碼,供大傢參考,具體內容如下

代碼:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
  <script src="https://lib.baomitu.com/jquery/3.5.1/jquery.js"></script>
</head>
<body>
 <div id="main" style="width: 600px;height:400px;"></div>
 <select name="" id="start" onchange="chooseYear2()">
  <option value="">1949</option>
 </select>

 <select name="" id="end"> 
 <option value=""></option>
 </select>

 <script type="text/javascript">
  var date = new Date();
  var y = date.getFullYear()
  function chooseYear1() {
   for (let i = 1949; i<=y; i ++) {
    let start = document.getElementById("start");
    let year = Number(start.lastElementChild.innerHTML) + 1;
    var myOption = document.createElement("option");
    myOption.innerHTML = year;
    start.appendChild(myOption);
   }
  }
  chooseYear1();
  function chooseYear2() {
  //如果你想讓起始年份下拉框和結束年份下拉框都顯示從1949至今的年份,那麼寫同樣的循環即可:
   let end = Number($("#start").find("option:selected").val());
   let start = document.getElementById("end");
   start.firstElementChild.innerHTML=end;
   var myOption = document.createElement("option");
   for (let i = end; i<=y; i ++) {
    let start = document.getElementById("end");
    let year = Number(start.lastElementChild.innerHTML) + 1;
    var myOption = document.createElement("option");
    myOption.innerHTML = year;
    start.appendChild(myOption);
   }
  }
 </script>
</body>
</html>

隻顯示年份的下拉框效果:

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: