javascript - 如何使倒计时可与对象重复使用?

标签 javascript oop

我有一个在点击事件时运行的倒计时。我需要使这个程序面向对象。我想用构造函数创建一个对象,这样我的倒计时就可以在我想要的每个 div 中运行。如果有人可以向我展示如何使用构造函数创建一个清晰的对象,并在 main.js 文件中调用它,我将能够将我想要的目标 div 的 id 放入参数中。

html

</button>

<div id="target">

</div>

<div id="targetbis">

</div>

js倒计时

var timeout;


function countdownto(target, time, callback) {
    var finish = new Date(time);
    var s = 1000,
        m = s * 60,
        h = m * 60,
        d = h * 24;

    (function timer() {
        var now = new Date();
        var dist = finish - now;

        var days = Math.floor(dist / d),
            hours = Math.floor((dist % d) / h),
            minutes = Math.floor((dist % h) / m),
            seconds = Math.floor((dist % m) / s);

        var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
        target.innerHTML = timestring

        clearTimeout(timeout);

        if (dist > 0) {
            timeout = setTimeout(timer, 1000);
        } else {
            callback()
        }

    })()

}

运行倒计时的js

let runningBtn = document.getElementById("runningbutton")

runningBtn.addEventListener("click", function(e) {


              clearTimeout(timeout);
            // countdown element
            var countdownel = document.getElementById('target');

            // 20 min
            var time = new Date()
            time.setSeconds(time.getSeconds() + 1200)


            // countdown function call
            countdownto(countdownel, time, function() {
                alert('finished');
            })


        })

我想在 main.js 中添加什么内容

let newCountdown = new Countdown("target");
let newnewCountdown = new Countdown("targetbis");

最佳答案

对象由三部分组成:构造函数、成员方法和成员变量。

// constructor
function Countdown(target,btn){
    // member variable
    this.target = target
    this.btn = btn
    this.btn.addEventListener("click", function(e) {
            clearTimeout(timeout);
            var time = new Date()
            time.setSeconds(time.getSeconds() + 1200)
            // countdown function call
            this.countdownto(this.target, time, function() {
                alert('finished');
            })
        })
}
// member method
Countdown.prototype.countdownto = function(){
    ...
}

在 es6 语法中,它看起来像:

class Point {
  // constructor 
  constructor(x, y) {
    // member variable 
    this.x = x;
    this.y = y;
  }

   // member method 
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

关于javascript - 如何使倒计时可与对象重复使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57288768/

相关文章:

javascript - react native : sending events from android to javascript

javascript - 通过引用传递数组不起作用

c# - 如何检测彼此靠近的两个窗口

oop - typescript 父类正在调用派生函数

javascript - jquery 类更改时更改 href 函数

javascript - 如何通过SW在AMP页面中包含自定义JS?

php - 开闭原则——如何调用新版本?

c++ - 覆盖矩阵中 vector 对象的代理类中的赋值运算符?

javascript - Jquery/JavaScript 在本地运行,但不在服务器上运行

java - Java中的子类和父类(super class)