jQuery Mobile - 将选项设置为月份

时间:2018-03-10 16:58:36

标签: javascript jquery-mobile

我在JQM 1.4.5中有一个如下所示的选择字段:

<div class="ui-field-contain">
    <select class="myMonthSel" name="select-native-2" id="select-native-2 monthSel" data-mini="true">
         <OPTION value="NONE">Select a date</OPTION>
    </select>
</div>

我正在尝试从最近一个月开始的几个月动态加载选项。我目前使用的功能如下所示:

function populateMonths() {

var months = {
    "0": "January",
    "1": "February",
    "2": "March",
    "3": "April",
    "4": "May",
    "5": "June",
    "6": "July",
    "7": "August",
    "8": "September",
    "9": "October",
    "10": "November",
    "11": "December"
};

var monthSel = $('.myMonthSel');

console.log(monthSel.length);
var curDate = new Date;

for (var i = 0; i < 12; i++) {
    var val = (curDate.getMonth() + i) % 12;
    console.log(months[val]);
    monthSel.options[monthSel.length] = new Option(months[val], i);
}
} populateMonths();

我在控制台中收到错误:

  

TypeError:无法设置属性&#39; 2&#39;未定义的

我尝试了一些不同的选项,包括将选择器更改为 $(&#39; .myMonthSel&gt;选项)并使用数组代替对象数月。

我不确定我做错了什么不显示。我在这里有一个有效的jfiddle函数:https://jsfiddle.net/75exLm8a/11/

谢谢。

1 个答案:

答案 0 :(得分:1)

保持简单:

function populateMonths() {
  var months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ],
  curMonth = new Date().getMonth(),
  html = '<option data-placeholder="true">Select a date</option>';
  for (var i = 0; i < 12; i++) {
    var val = (curMonth + i) % 12;
    var monthName = months[val];
    var isoMonth = ("0"+(months.indexOf(monthName)+1)).substr(-2);
    html += '<option value="'+isoMonth+'">'+monthName+'</option>';
  }
  $('#select-month').html(html).selectmenu("refresh");
}

$(document).on("pagecreate", "#page-one", function() {
  populateMonths();
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
</head>
<body>
  <div id="page-one" data-role="page">
    <div role="main" class="ui-content">
      <div class="ui-field-contain">
        <select id="select-month" name="select-month" class="myMonthSel" data-native-menu="false" data-mini="true">
        </select>
      </div>
    </div>
  </div>
</body>
</html>