如何将此脚本转换为$(document).ready构造?

时间:2013-11-11 14:10:39

标签: jquery

我的语法有些问题:( 在哪里以及如何需要关闭准备好?此脚本必须仅在加载页面后加载。

function wr_hours(item){
//timeout
var sek = item.data("timeout");
var min = Math.floor((sek /60)%60) ;//sec
var hour = Math.floor((sek / (60*60)) %24) ;//hr
var days = Math.floor(sek /(24*60*60)) ;//days
var counterWrapper = $("#b-countdown");

if ( min < 10 ){
    min = "0" + min;
}
//CSS       
if ( hour != counterWrapper.data("left") ){
    var hourClass = hour == 0 ? 1 : hour;
    counterWrapper.attr("class", "left-" + hourClass).attr("data-left", hourClass)
}

var time_wr = hour + ":" + min;
item.html(time_wr);
item.data("timeout", (sek - 1) > 0 ? sek - 1 : 24 * 60 * 60);
}
setInterval(function(){
    $(".deadline").each(function(){ wr_hours($(this));})
}, 1000);

2 个答案:

答案 0 :(得分:1)

你的意思是:

$(document).ready(function() {
    function wr_hours(item){
        //timeout
        var sek = item.data("timeout");
        var min = Math.floor((sek /60)%60) ;//sec
        var hour = Math.floor((sek / (60*60)) %24) ;//hr
        var days = Math.floor(sek /(24*60*60)) ;//days
        var counterWrapper = $("#b-countdown");

        if ( min < 10 ){
            min = "0" + min;
        }
        //CSS       
        if ( hour != counterWrapper.data("left") ){
            var hourClass = hour == 0 ? 1 : hour;
            counterWrapper.attr("class", "left-" + hourClass).attr("data-left", hourClass)
        }

        var time_wr = hour + ":" + min;
        item.html(time_wr);
        item.data("timeout", (sek - 1) > 0 ? sek - 1 : 24 * 60 * 60);
    } setInterval(function(){
        $(".deadline").each(function(){ wr_hours($(this));})
    }, 1000);
});

但是,由于您在wr_hours函数中调用函数setInterval,另一种方法是将setInterval部分放在$(document).ready(function() { ... });

答案 1 :(得分:1)

JQuery ready函数可以像这样使用:

$(document).ready(function () {
/* ADD YOUR CODE HERE */
});

在你的例子中:

function wr_hours(item){
    //timeout
    var sek = item.data("timeout");
    var min = Math.floor((sek /60)%60) ;//sec
    var hour = Math.floor((sek / (60*60)) %24) ;//hr
    var days = Math.floor(sek /(24*60*60)) ;//days
    var counterWrapper = $("#b-countdown");

    if ( min < 10 ){
        min = "0" + min;
    }
    //CSS       
    if ( hour != counterWrapper.data("left") ){
        var hourClass = hour == 0 ? 1 : hour;
        counterWrapper.attr("class", "left-" + hourClass).attr("data-left", hourClass)
    }

    var time_wr = hour + ":" + min;
    item.html(time_wr);
    item.data("timeout", (sek - 1) > 0 ? sek - 1 : 24 * 60 * 60);
}
$(document).ready(function() {
    setInterval(function(){
        $(".deadline").each(function(){ wr_hours($(this));})
    }, 1000);
});