【发布时间】:2018-10-17 17:24:57
【问题描述】:
我有下面的代码,我相信 $this 没有在 if 语句中触发,因为它没有添加任何一个类。但是,如果我将其更改为只查找没有 $this 的类,它会添加两个类(因为我在页面上有 2 个优惠券,1 个触发 if 和 1 个触发 elseif)。我不确定如何在 if 语句中触发 $this.find()。
jQuery(document).ready(function($) {
if ($('.clockdiv')[0]) {
$('.couponWrap .coupons li').each(function() {
// Set the date we're counting down to
var deadlineYear = $(this).find("div .clockdiv .year").attr("rel");
var deadlineMonth = $(this).find("div .clockdiv .month").attr("rel");
var deadlineDay = $(this).find("div .clockdiv .days").attr("rel");
var deadlineHour = $(this).find("div .clockdiv .hours").attr("rel");
var deadlineMinute = $(this).find("div .clockdiv .minutes").attr("rel");
var deadlineSecond = $(this).find("div .clockdiv .seconds").attr("rel");
var couponExpired = $(this).find("div .clockdiv").attr("rel");
var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
var startDate = new Date($(this).find("div .clockdiv .start").attr("rel"));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}
//Works but only for 1st start date
//var testDate = $("div .clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var startDateNewer = new Date(startDate);
var newOldDate = new Date(startDateNewer.setDate(startDateNew.getDate() + 7));
//alert(startDate + ", " + startDateNew + ", " + startDateNewer + ", " + newOldDate);
//This works fine
var nowDateNew = new Date().getTime();
//alert(nowDateNew - newOldDate.getTime());
if (days <= 7) {
$(this).find('div.couponDiv').addClass("old-coupon");
} else if ((nowDateNew - newOldDate.getTime()) < 0) {
$(this).find('div.couponDiv').addClass("new-coupon");
}
}, 1000);
});
}
});
有问题的具体代码sn-p是:
if (days <= 7) {
$(this).find('div.couponDiv').addClass("old-coupon");
} else if ((nowDateNew - newOldDate.getTime()) < 0) {
$(this).find('div.couponDiv').addClass("new-coupon");
}
【问题讨论】:
-
感谢您对此发表评论,我将 self 定义为 $(this) 并使用它,很有魅力。你是明星!
标签: javascript jquery function each