简体   繁体   English

多个JavaScript倒计时

[英]Multiple JavaScript countdowns

<?php wpsc_start_category_query(array('category_group'=>get_option('wpsc_default_category'), 'show_thumbnails'=> 1)); ?>

<script>
window.onload = function() {
    countdown('countdown<?php wpsc_print_category_id(); ?>');
}
var interval;

var seconds = 5;
function countdown(element) {
    interval = setInterval(function() {
        var el = document.getElementById(element);
        if(seconds == 0) {
         el.innerHTML = "countdown's over!";                    
         clearInterval(interval);
         return;
        }
        el.innerHTML = seconds + ' seconds remaining';
        seconds--;
    }, 1000);
}
</script>

<div id='countdown<?php wpsc_print_category_id(); ?>'></div>
<?php wpsc_end_category_query(); ?>

my task it display such countdown for every wp query. 我的任务是为每个wp查询显示这样的倒计时。 the problem is that it only displays for the last queried object. 问题是它仅显示最后一个查询的对象。 My guess is that's becaus window.onload, but I cant think any alternative 我的猜测是因为window.onload,但是我想不到

Any Help? 有帮助吗?

I don't 100% understand what the WP stuff does so this might just be total rubbish! 我不是100%了解WP的功能,所以这可能完全是垃圾!

My code has 2 parts, a part to use in-place of your current code, the template, and a portion of code to have in your page <head> , the countdown function. 我的代码分为两部分,一部分用于替换您当前的代码,模板,另一部分包含在页面<head> (倒数功能)中。

There's also a function to convert seconds into days,hours,mins and seconds should your interval not be constant at 5 seconds in the future. 如果将来间隔不固定为5秒,还有一个功能可以将秒转换为天,小时,分钟和秒。

The countdown function will update all countdowns that are set-up by the template code. 倒数计时功能将更新模板代码设置的所有倒数计时。

Hope it helps :) 希望能帮助到你 :)

Update 更新资料

My code does not edit or delete anything on your server, obviously named my variable a little too close to home for you :) As my comment says, the delete call only removes the counter from the list holding information about the counters, removing the delete statement will leave finished counters in the list (not a problem, just less efficient as they are iterated over when tick() gets called) 我的代码不会编辑或删除您服务器上的任何内容,显然将我的变量命名为离您太近了:)正如我的评论所说, delete调用仅从包含有关计数器信息的列表中删除计数器,从而删除删除语句将把完成的计数器留在列表中(这不是问题,只是效率较低,因为它们在调用tick()会被迭代)

I will try to describe what my code does at the bottom so you can understand better what is going on. 我将尝试在底部描述我的代码的作用,以便您可以更好地了解发生了什么。

WPSC Template WPSC模板

<?php   wpsc_start_category_query(array('category_group'=>get_option('wpsc_default_category'), 'show_thumbnails'=> 1)); ?>
<script type="text/javascript">
if (!wpsc_categories) { wpsc_categories = {}; }
wpsc_categories['countdown_<?php wpsc_print_category_id(); ?>'] = 5; // this value is the countdown in seconds
</script>
<div id="countdown_<?php wpsc_print_category_id(); ?>"></div>
<?php wpsc_end_category_query(); ?>

If you want a 1 week countdown and for the countdown to persist over page views (so it does not reset to 1 week when you refresh) you will need to store a counter start date on your server, calculate the difference between then and now (with php) and use that in-place of 5 ( I guess that is what you planned on doing anyway though! ) 如果您希望倒计时为1周,并且要让倒计时在页面浏览量中持续存在(因此刷新时不会重置为1周),则需要在服务器上存储计数器的开始日期,计算此时与现在之间的差值(并使用php),并在其中使用5(我想这还是您计划要做的!)

Countdown Function - This should be included in the header of your page 倒数计时功能-此功能应包含在页面标题中

<script type="text/javascript">
var wpsc_categories = [];

// the following function will update all counters using one timer (hopefully)
function tick() {
    var element;
    for (category in wpsc_categories) {
        if (wpsc_categories.hasOwnProperty(category)) {
            element = document.getElementById(category);
            if (wpsc_categories[category] == 0) {
                element.innerHTML = "countdown over!";
                delete wpsc_categories[category];
            } else {
                // MODIFIED THIS LINE, SEE NOTE
                //element.innerHTML = formatTime(wpsc_categories[category]--);
                element.innerHTML = formatTime(wpsc_categories[category]);
                wpsc_categories[category] -= 1;
            }
        }
    }
    //return setInterval(tick, 1000); //this line is bad :D
}

var interval = setInterval(tick, 1000) // start it running

// return formatted time from seconds (if required)
function formatTime(seconds) {
    var numdays = Math.floor(seconds / 86400);
    var numhours = Math.floor((seconds % 86400) / 3600);
    var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
    var numseconds = ((seconds % 86400) % 3600) % 60;
    return (numdays>0?numdays+" days ":"")+(numhours>0?numhours+" hours ":"")+(numminutes>0?numminutes+" minutes ":"")+(numseconds>0?numseconds+" seconds":"")
}
</script>

Note 注意

I changed the way the remaining time is updated to make it a little more clear. 我更改了剩余时间的更新方式,使其更加清晰。 I used a decrement operator -- which can be a little annoying. 我使用了减量运算符--可能有点烦人。

Description 描述

Your original template copied a large block of code for every category, including the countdown code and the call that invokes it, which is why only the last categories timer was working. 您的原始模板为每个类别复制了一大段代码,包括倒计时代码和调用它的调用,这就是为什么只有最后一个类别计时器才起作用的原因。 window.onload was being overwritten by each subsequent category. window.onload被随后的每个类别覆盖。

Yes you could have used an anonymous function to start the function rolling and it should have worked, but its probably not the best solution. 是的,您本可以使用匿名函数来启动函数滚动,并且应该可以正常工作,但它可能不是最佳解决方案。

Now for my code 现在我的代码

you had a question about if (!wpsc_categories) { wpsc_categories = {}; } 您对if (!wpsc_categories) { wpsc_categories = {}; } if (!wpsc_categories) { wpsc_categories = {}; } wpsc_categories is an object that stores information about counters. if (!wpsc_categories) { wpsc_categories = {}; } wpsc_categories是一个存储有关计数器信息的对象。 this checks to see if the object exists and creates it if it does not so that the next like can add information about a counter. 这将检查对象是否存在,如果不存在则创建该对象,以便下一个对象可以添加有关计数器的信息。

In the browser, your client would get the following for 3 example groups. 在浏览器中,您的客户端将获得3个示例组的以下内容。

<script type="text/javascript">
if (!wpsc_categories) { wpsc_categories = {}; }
wpsc_categories['countdown_example1'] = 5;
</script>
<div id="countdown_example1"></div>
<script type="text/javascript">
if (!wpsc_categories) { wpsc_categories = {}; }
wpsc_categories['countdown_example2'] = 5;
</script>
<div id="countdown_example2"></div>
<script type="text/javascript">
if (!wpsc_categories) { wpsc_categories = {}; }
wpsc_categories['countdown_example3'] = 5;
</script>
<div id="countdown_example3"></div>

As soon as the code in this block is executed by javascript the wpsc_categories variable will be filled with information about the 3 required counters. 一旦此代码块中的代码由javascript执行,wpsc_categories变量就会填充有关3个必需计数器的信息。 This information is what tick() uses to update the timers. 此信息是tick()用于更新计时器的信息。

Update 2 My example used setInterval inside the tick() function, which was bad! 更新2我的示例在tick()函数内部使用了setInterval ,这很糟糕! as setInterval is a repeating timer, so every call to tick created a new timer and so it would change the time exponentially :D 由于setInterval是一个重复的计时器,因此每次对tick的调用都会创建一个新计时器,因此它将以指数方式更改时间:D

setTimeout() is one-shot, setInterval() keeps going till you stop it! setTimeout()是一次性的, setInterval()一直持续到您停止为止!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM