JavaScript增量计数器没有新鲜感

时间:2014-08-30 01:59:51

标签: javascript jquery smarty

我想在smartry(.tpl)文件中使用此计数器。我发现脚本链接在下面

DEMO

我只是想知道我应该把这些脚本代码放在哪里

var START_DATE = new Date("October 10, 2012 22:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 30; // increase per tick
var START_VALUE = 35001; // initial value when it's the start date
var count = 0;

$(document).ready(function() {
 var msInterval = INTERVAL * 1000;
 var now = new Date();
 count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
 document.getElementById('counter').innerHTML = count;

 window.setInterval( function(){
    count += INCREMENT; 
    document.getElementById('counter').innerHTML = count;
 }, msInterval);

});

我的意思是把它们放在哪里或?我想在smarty(.tpl)文件中使用它们。引导我,因为我是javascript的新手。

1 个答案:

答案 0 :(得分:0)

您可以根据需要将此代码放入Smarty模板或JS文件中。

当然你还需要加载jQuery。

下面有一个完整的Smarty .tpl文件,它使用您的代码并且没有问题:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo counter</title>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>


<div id="counter">


</div>

<script type="text/javascript">
    {literal}
    var START_DATE = new Date("October 10, 2012 22:30:00"); // put in the starting date here
    var INTERVAL = 1; // in seconds
    var INCREMENT = 30; // increase per tick
    var START_VALUE = 35001; // initial value when it's the start date
    var count = 0;

    $(document).ready(function () {
        var msInterval = INTERVAL * 1000;
        var now = new Date();
        count = parseInt((now - START_DATE) / msInterval) * INCREMENT + START_VALUE;
        document.getElementById('counter').innerHTML = count;

        window.setInterval(function () {
            count += INCREMENT;
            document.getElementById('counter').innerHTML = count;
        }, msInterval);

    });
    {/literal}
</script>

</body>
</html>