我有一个jQuery函数,可以计算两个给定时间(hh:mm格式)之间的小时和分钟。它工作得很好,但我正在尝试将这个函数应用于我的HTML结构中的每个项目。每个项目都包含在一个类.item
我的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 .each()函数来计算部分每个项目的小时数?或者有更好的方法吗?
JSFiddle:http://jsfiddle.net/44NCk/8/
谢谢!
答案 0 :(得分:5)
循环浏览calculate
功能中的所有项目。
$(function () {
function calculate() {
$(".item").each(function(){
var $start = $(this).find(".start"),
$end = $(this).find(".end"),
$result = $(this).find(".hours"),
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
$result.val(hours + ':' + mins);
});
}
$(".start,.end").on("change", calculate);
$("#calculate").on("click", calculate);
calculate();
});
答案 1 :(得分:3)
您可以使用.each执行此操作并将$(this)元素传入您的方法。
$('.item').each(function() { //foreach element with a class of item.
calculate($(this)); //pass in the current element into your function.
});
function calculate($currentElement) {
time1 = $currentElement.find(".start").val().split(':'), //find the element with a start class within the $current element.
time2 = $currentElement.find(".end").val().split(':'); //find end class
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;
}
$currentElement.find(".hours").val(hours + ':' + mins); //find hours class and set value to calculated value.
}