首页 > 解决方案 > 除了其他,希利奥斯倒数计时器

问题描述

我想知道,如果有这样的方法,编辑 Hilios 倒数计时器,描述如下:

我有一个可以正常工作的函数,可以从日期开始倒计时(我想标记一下,我在单个视图中确实有几个日期,其中使用了计时器,所以我必须使用每个函数):

$('[data-countdown]').each(function() {
    var $this = $(this);
    var finalDate = $(this).data('countdown');
    $this.countdown(finalDate, function(event) {
        $this.html(event.strftime('%D days %H:%M:%S'));
    });
});

问题来了。由于此脚本“静态”工作 - 我的意思是静态 - 它从 html 获取日期并在加载脚本时将其传递到脚本中。

我的应用程序动态工作,因此日期也动态更改。

所以问题是:有没有这样的方法来编辑这个脚本,使用动态数据——当网站上的一些数据更新时,它也会更新倒数计时器中的数据

此致!PS。

标签: javascriptjquerytimercountdown

解决方案


请查看MutationObserver

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = {
  attributes: true,
  attributeFilter: ['data-timer'],
  attributeOldValue: true,
};

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
  for (var mutation of mutationsList) {
    console.log('CHANGED', mutation.oldValue);
  }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
//observer.disconnect();
<div id="some-id" data-timer="123">hello</div>
<button onclick="document.getElementById('some-id').setAttribute('data-timer', +new Date())">change</button>


推荐阅读