如何将元素传递给jquery中的匿名函数?
How to pass element to anonymus function in jquery?
我正在创建一个倒计时元素,我想将每个元素传递给 setinterval 函数以每秒更新一次
var countDownDate = new Date($(this).data('date')).getTime();
setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$(this).find('.days').text(days);
$(this).find('.hours').text(hours);
$(this).find('.minutes').text(minutes);
$(this).find('.seconds').text(seconds);
}, 1000);
});
提前致谢
你的问题没有描述你真正想要的,但是有几种方法可以在函数内访问这些元素。
- 使用箭头函数
setInterval(() => {
/*
your code goes here without changes
*/
}, 1000)
- 传递参数
setInterval(function(days, hours, minutes, seconds) {
/*
your code goes here without changes
*/
days.text(days);
hours.text(hours);
minutes.text(minutes);
seconds.text(seconds);
}, 1000, $(this).find('.days'), $(this).find('.hours'), $(this).find('.minutes'), $(this).find('.seconds'))
- 绑定
setInterval((function() {
/*
your code goes here without changes
*/
}).bind(this), 1000)
您也可以将 this
作为参数传递。
我会使用箭头函数,因为它是一种更现代的方法。
我正在创建一个倒计时元素,我想将每个元素传递给 setinterval 函数以每秒更新一次
var countDownDate = new Date($(this).data('date')).getTime();
setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$(this).find('.days').text(days);
$(this).find('.hours').text(hours);
$(this).find('.minutes').text(minutes);
$(this).find('.seconds').text(seconds);
}, 1000);
});
提前致谢
你的问题没有描述你真正想要的,但是有几种方法可以在函数内访问这些元素。
- 使用箭头函数
setInterval(() => {
/*
your code goes here without changes
*/
}, 1000)
- 传递参数
setInterval(function(days, hours, minutes, seconds) {
/*
your code goes here without changes
*/
days.text(days);
hours.text(hours);
minutes.text(minutes);
seconds.text(seconds);
}, 1000, $(this).find('.days'), $(this).find('.hours'), $(this).find('.minutes'), $(this).find('.seconds'))
- 绑定
setInterval((function() {
/*
your code goes here without changes
*/
}).bind(this), 1000)
您也可以将 this
作为参数传递。
我会使用箭头函数,因为它是一种更现代的方法。