gpt4 book ai didi

javascript - jQuery Mobile - 将选择选项设置为月份

转载 作者:行者123 更新时间:2023-12-03 02:19:46 25 4
gpt4 key购买 nike

我在 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: Cannot set property '2' of undefined

我尝试了一些不同的选项,包括将选择器更改为$('.myMonthSel > option) 并使用数组而不是对象几个月。

不知道我做错了什么才不会出现。我有一个工作jfiddle,其功能如下:https://jsfiddle.net/75exLm8a/11/

谢谢。

最佳答案

保持简单:

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>

关于javascript - jQuery Mobile - 将选择选项设置为月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com