从div标签中查找数字并计算总数

时间:2013-01-30 01:47:41

标签: javascript jquery html

我有一个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

希望它很清楚。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

Another alternative

// 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));