gpt4 book ai didi

javascript - 带有 setTimeout 或 setInterval 的 jQuery 插件

转载 作者:行者123 更新时间:2023-11-30 10:44:37 24 4
gpt4 key购买 nike

我正在开发我的第一个 jQuery 插件,它是一个简单的倒数计时器,带有一个用于设置目标日期的选项。目标是让纯文本时钟倒计时到提供的目标日期和时间。对于我的生活,我无法弄清楚如何在插件中使用 setTimeout 或 setInverval,所以它实际上是倒计时。一整天都在研究 stackoverflow 和其他资源,但找不到解决方案,如果我没有得到解决方案,我们深表歉意。

这是我得到的:

(function( $ ){

$.fn.clock = function( options ) {

// ESTABLISH DEFAULTS
var settings = $.extend( {
'target' : '07/21/2013 09:00:00', // mm/dd/yyyy hh:mm:ss
}, options);

return this.each(function() {

// calculate milliseconds to target
tarDate = new Date(settings.target);
dateNow = new Date();
amount = tarDate.getTime() - dateNow.getTime();
delete dateNow;

// set label
label = settings.title;

// generate output
if(amount <= 0) {
out = '000:00:00:00';
} else {
td = 0; th = 0; tm = 0; ts = 0; out = ''; // reset everything
amount = Math.floor(amount/1000); // kill the milliseconds
td = Math.floor(amount/86400); // calculate days to target
amount = amount%86400; // convert amount to days
th = Math.floor(amount/3600); // calculate hours to target
amount = amount%3600; // convert amount to hours
tm = Math.floor(amount/60); // calculate minutes to target
amount = amount%60; // convert amount to minutes
ts = Math.floor(amount)+1; // calculate seconds to target

out += (td<=99?'0':'') + (td<=9?'0':'') + td + ':';
out += (th<=9?'0':'') + th + ':';
out += (tm<=9?'0':'') + tm + ':';
out += (ts<=9?'0':'') + ts;
}

// assemble and pump out to dom
$(this).html(out);

// set refresh rate
??????

});

};
})( jQuery );

最佳答案

查看 this link用于插件创作的有趣模式。基本上您需要做的是提供一种更新时钟的“方法”:

(function( $ ){

function updateClock(element) {
var settings = element.data("settings");
// Your update logic goes here
}

$.fn.clock = function( options ) {
if ( options === 'update' )
return updateClock(this);
// Other methods, if any
else if ( typeof options !== 'object' )
throw 'Unknown method';

// ESTABLISH DEFAULTS
var settings = $.extend( {
'target' : '07/21/2013 09:00:00', // mm/dd/yyyy hh:mm:ss
}, options);

// Save your settings for later access
this.data("settings",settings);

然后,每次你想更新一个元素,你这样调用它:

$(yourselector).clock("update");

(从外部;如果 updateClock 可以从您的作用域访问,您可以直接调用它以提高效率。只要记得在必要时将元素包装在 $() 中)

最后,您必须配置setTimeoutsetInterval。我更喜欢 setTimeout,因为这将允许您在必要时停止或重新启动时钟。将此添加到您的 updateClock 的末尾,可能之前有一个检查:

setTimeout(function() { updateClock(element); }, settings.refreshRate);

关于javascript - 带有 setTimeout 或 setInterval 的 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com