Javascript 动态时间下拉
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8918168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Dynamic Time Drop Down
提问by Matt
I'm not very good at Javascript Time manipulation.
我不太擅长 Javascript 时间操作。
Here is what I am trying to do: I have a UI that needs a end time drop down list. Its a finite set of times, essentially from 7:00 AM to 10:00 PM in 15 minute increments. I'm using jQuery and want to create on the fly a Select box that looks like this:
这是我想要做的:我有一个需要结束时间下拉列表的 UI。它是一组有限的时间,基本上是从早上 7:00 到晚上 10:00,以 15 分钟为增量。我正在使用 jQuery 并想动态创建一个如下所示的选择框:
<select>
<option value="420">7:00 AM</option>
<option value="435">7:15 AM</option>
<option value="450">7:30 AM</option>
etc...
</select>
Anyone know how to do this in javascript/jQuery. I want to do something dynamic like this:
任何人都知道如何在 javascript/jQuery 中做到这一点。我想做一些像这样动态的事情:
for(int i = 420; i<=1320; i+=15){
//use value of i to increment a date or something and create an option for the drop down... this is where I am stuck
}
回答by Li0liQ
The following snippet should help you get the idea:
以下代码段应该可以帮助您了解这个想法:
function populate(selector) {
var select = $(selector);
var hours, minutes, ampm;
for(var i = 420; i <= 1320; i += 15){
hours = Math.floor(i / 60);
minutes = i % 60;
if (minutes < 10){
minutes = '0' + minutes; // adding leading zero
}
ampm = hours % 24 < 12 ? 'AM' : 'PM';
hours = hours % 12;
if (hours === 0){
hours = 12;
}
select.append($('<option></option>')
.attr('value', i)
.text(hours + ':' + minutes + ' ' + ampm));
}
}
populate('#timeSelect'); // use selector for your select