我有一个jQuery函数,它可以计算两个给定时间(hh:mm格式)之间的小时和分钟。它工作得很好,但我正在尝试为我的HTML结构中的每个项目应用此函数。每个项目都裹成一个div类.item
为每个具有某个类的元素运行jQuery函数
我的HTML:
<div class="item">
<label for="start">Start</label>
<input class="start" id="start" value="10:00" />
<label for="end">End</label>
<input class="end" id="end" value="12:15" />
<label for="hours">Hours</label>
<input class="hours" id="hours" value="" readonly />
</div>
<div class="item">
<label for="start">Start</label>
<input class="start" id="start" value="10:00" />
<label for="end">End</label>
<input class="end" id="end" value="13:30" />
<label for="hours">Hours</label>
<input class="hours" id="hours" value="" readonly />
</div>
<button id="calculate" onclick="calculate()">Calculate</button>
脚本:
$(function() {
function calculate() {
time1 = $(".start").val().split(':'),
time2 = $(".end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$(".hours").val(hours + ':' + mins);
}
$(".start,.end").change(calculate);
calculate();
});
我的问题是:如何申请jQuery的。每()函数来计算每个项目的小时数部分?或者有更好的方法呢?
的jsfiddle:http://jsfiddle.net/44NCk/8/
谢谢!
你说的意思是“部分” – PlaceUserNameHere
例如,像这样:http://jsfiddle.net/44NCk/10/ –
计算上使用单击事件只是另一个例子,你的起始小提琴有一个错误记住,当在$(function(){})中声明一个函数时,我们不会在全局范围内。 http://jsfiddle.net/44NCk/11/ –