-6

我有一个html文本如下

<div class="co"><b>op</b> (11:32:20): here some string</div>
<div class="cv"><b>cl</b> (11:32:42): here some another string</div>
<div class="co"><b>op</b> (11:33:15): another...</div>
<div class="co"><b>cl</b> (11:33:36): another...</div>
<div class="cv"><b>op</b> (11:33:45): another...</div>
<div class="co"><b>cl</b> (11:34:46): another...</div>
<div class="cv"><b>op</b> (11:35:00): another...</div>
<div class="co"><b>cl</b> (11:37:19): another...</div>

如何从上面的示例中获取第一个 div 编号和最后一个 div 编号。在这种情况下,第一个 div 编号is 11:32:20和最后一个 div 编号11:37:19,我想计算差异,例如 11:37:19减去11:32:20

希望很清楚。

4

2 回答 2

0
function getSeconds(time){
    var tokens = time.split(":");
    var seconds = parseInt(tokens[2]);
    seconds += parseInt(tokens[1]) * 60;
    seconds += parseInt(tokens[0]) * 60 *60;
    return seconds;
}

var divs = $(".co,.cv");
var firstHtml = $(divs.eq(0)).html();
var lastHtml = $(divs.eq(divs.length-1)).html();
var firstValue = firstHtml.substring(firstHtml.indexOf("(") +1, firstHtml.indexOf(")"));
var lastValue = lastHtml.substring(firstHtml.indexOf("(") +1, firstHtml.indexOf(")"));

var diff = getSeconds(lastValue) - getSeconds(firstValue);

console.log(diff);

示例:http: //jsfiddle.net/CRQFk/

于 2013-01-30T02:00:27.003 回答
0

另一种选择

// parses the hh:mm:ss out of the div's text
function timeStrToDate(str){
    // look for hh:mm:ss and extract it
    var m = str.match(/(\d{1,2}:\d{1,2}:\d{1,2})/);
    if(m){
        // we were able to locate it, so convert it to a Date
        // (we only care about time, so use epoc as a ref. point)
        return new Date('Thu, 01 Jan 1970 ' + m[1]);
    }
    // return an empty time by default
    return new Date('Thu, 01 Jan 1970');
}
// converts straight seconds in to hh:mm:ss
function secondsToTime(sec){
    var r = [], d
    // go through by hours, minutes then seconds
    // and divide then subtract each time
    var exp = [3600,60,1];
    for (e = 0; e < exp.length; e++){
        if (sec >= exp[e]){
            d = Math.floor(sec / exp[e]);
            sec -= d * exp[e];
            r.push(d < 10 ? '0'+d : d); // pad it so 9 becomes 09
        }
    }
    return r.join(':');
}

// the actual jQuery code

// grab all divs
var $divs = $('div.co,div.cv');
// Grab first element, get text, and parse the time out
var $first = timeStrToDate($divs.first().text()),
    // do the same with the last
    $last = timeStrToDate($divs.last().text()),
    // get the difference (returned in seconds elapsed)
    $delta = Math.abs($last - $first) / 1e3; // `/1e3` -> milliseconds to seconds

 // here's the end result, 4:59 in this case
console.log(secondsToTime($delta));
于 2013-01-30T02:14:40.683 回答