【问题标题】:Javascript Adds Same Class To Divs Without Calculating For Each DivJavascript 将相同的类添加到 Div 而不为每个 Div 计算
【发布时间】:2018-09-28 18:57:35
【问题描述】:

我展示了 2 张优惠券,它们都有 .new-coupon,而实际上其中一张应该是 .new-coupon,而一张应该是 .old-coupon。它似乎为页面上的每个元素应用相同的类,而不是计算每个元素应该是哪个类。

jQuery(document).ready(function($) {
// Set the date we're counting down to
  var deadlineYear = $("#clockdiv .year").attr("rel");
  var deadlineMonth = $("#clockdiv .month").attr("rel");
  var deadlineDay = $("#clockdiv .days").attr("rel");
  var deadlineHour = $("#clockdiv .hours").attr("rel");
  var deadlineMinute = $("#clockdiv .minutes").attr("rel");
  var deadlineSecond = $("#clockdiv .seconds").attr("rel");
  var couponExpired = $("#clockdiv").attr("rel");

  var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();

  // 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>";
}

var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00

  var startDateNew = new Date(startDate);
  var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
  var nowDateNew = new Date(now);

  if (days <= 7) {
      $('.couponDiv').addClass("old-coupon");
  } else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
      $('.couponDiv').addClass("new-coupon");
  }    
  }, 1000);
});

用于变量的 HTML:

<div id="clockdiv" rel="'.$expired.'">
<span class="start" rel="'.$start.'"></span>
<span class="year" rel="'.$year.'"></span>
<span class="month" rel="'.$month.'"></span>
<div><span id="days" class="days" rel="'.$day.'"></span><div class="smalltext">Days</div></div>
<div><span id="hours" class="hours" rel="'.$hour.'"></span><div class="smalltext">Hours</div></div>
<div><span id="minutes" class="minutes" rel="'.$minute.'"></span><div class="smalltext">Minutes</div></div>
<div><span id="seconds" class="seconds" rel="'.$second.'"></span><div class="smalltext">Seconds</div></div>
</div>

用于在优惠页面上显示优惠券的 HTML:

<li>
                    <?php
                    $year = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('Y');
                    $month = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('m');
                    $day = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('d');
                    $hour = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('H');
                    $minute = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('i');
                    $second = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('s');

                    $humanDate = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('D jS M Y');
                    $expiredText = get_field('offer_voucher_expired');
                    ?>
                <div style="display:none;">
                    <?php echo do_shortcode('[gw-countdown expired="'.$expiredText.'" year="'.$year.'" month="'.$month.'" day="'.$day.'" hour="'.$hour.'" minute="'.$minute.'" second="'.$second.'" start="'.get_field('offer_voucher_start').'"]');?>
                </div>
                <div id="couponDiv" class="couponDiv">
                    <h1><?php the_title();?></h1>
                    <div class="couponDetails">
                        <div class="couponView">
                            <?php $offer = get_field('offer_single_label', 'options'); $offerC = ucwords($offer);?>
                            <a class="button" href="<?php the_permalink();?>" title="See Offer Details">See <?php echo $offerC;?> Details</a>
                        </div>
                        <div class="couponValid">
                            <p class="bold">Valid Until:</p>
                            <p class="couponDate"><?php echo $humanDate;?></p>
                        </div>
                    </div>
                </div>
                </li>

编辑

我完全理解问题所在,并将代码更新为以下内容:

$('.couponDiv').each(function() {

    var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00
    var startDateNew = new Date(startDate);
    var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
    var nowDateNew = new Date(now);


    if (days <= 7) {
        $(this).addClass("old-coupon");
    } else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
        $(this).addClass("new-coupon");
    }
  }); 

但是,我不知道如何制作:

var startDate = $("#clockdiv .start").attr("rel");

应用到 $this 所以它的 $this #clockdiv .start 因为我相信它会起作用...

编辑

我修改了一行代码来阅读:

var startDate = $(this).find("#clockdiv .start").attr("rel");

现在这只会将课程添加到第一个报价而不是第二个报价,然后我尝试重复:

$(this).find()

围绕初始变量然后移动:

$('.couponDiv').each(function() {

然而,在文档就绪功能下方的顶部,这会停止添加任何类。

【问题讨论】:

  • 每个.coupon 中是否有一些东西可以用来评估新的或旧的?现在,您似乎使用相同的日期/时间来计算所有 coupon。 HTML 将有助于提供帮助。
  • @Steve0 我已经添加了所有相关的 HTML/PHP
  • 您只对整个应用程序进行一次日期计算,而不是为每张优惠券使用不同的日期重新计算。你也有 id="couponDiv" 和 class="couponDiv" 这很糟糕,两个元素不能有相同的 id
  • @Our_Benefactors 我知道这一点,这就是为什么我要问如何为每张优惠券多次运行它?
  • @DanielVickers 你需要使用 jQuery.each()

标签: javascript jquery datetime


【解决方案1】:
if (days <= 7) {
   $('.couponDiv').addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
   $('.couponDiv').addClass("new-coupon");
}

在上面的代码中,您选择了所有.couponDiv 来添加类old-coupon,然后再次选择所有.couponDiv 来添加类new-coupon。条件在这里没有意义,因为任何匹配你仍然为所有元素添加类。

您必须区分哪些元素属于“旧”,哪些元素属于“新”。然后分别添加类名。

【讨论】:

  • 我很欣赏指针,但我知道问题只是不知道如何解决它,正如赏金中提到的:“我正在寻找一个解决方案而不是指针。非常感谢。”
【解决方案2】:

这是你需要的吗?

var startDate = $(this).find("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00

【讨论】:

  • 我添加了这个,然后它只将类添加到第一个报价而不是第二个报价,然后我尝试在第一行之后添加 .each() 然后添加 $this().find ...对于所有变量,它停止添加所有类。
  • 实际测试它,这一半可以解决这个问题,但现在每个优惠券的 $days 都是相同的,所以我需要计算 .each() 的所有内容,但是当我移动上面的函数时它不起作用代码。
【解决方案3】:

经过一些重建和使用 $this 我能够得到这个工作:

$('.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"));

    var self = $(this);

    // 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) {
        self.find('div.couponDiv').addClass("old-coupon");
      } else if ((nowDateNew - newOldDate.getTime()) < 0) {
        self.find('div.couponDiv').addClass("new-coupon");
      }
    }, 1000);
  });

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 2013-01-07
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2018-04-10
    相关资源
    最近更新 更多