Javascript向Divs添加相同的类,而无需为每个Div计算 [英] Javascript Adds Same Class To Divs Without Calculating For Each Div

查看:70
本文介绍了Javascript向Divs添加相同的类,而无需为每个Div计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2张优惠券显示,它们都带有.new优惠券,而实际上一个人应该说.new优惠券而一个人应该说.old优惠券.似乎对具有该类的页面上的每个元素都应用了相同的类,而不是为每个元素计算应该属于哪个类.

I have 2 coupons showing, they both have the .new-coupon when in fact one should say .new-coupon and one should say .old-coupon. It seems to apply the same class for every element on the page with that class instead of calculating which class it should be for each element.

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:

HTML used for displaying the coupons on the offers page:

<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>

修改

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

I understand completely where the issue lies, and have updated the code to the following:

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

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

However, I do not know how to make:

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

应用于$ this,使其$ this #clockdiv .start生效,因为我相信它会起作用...

Apply to $this so its $this #clockdiv .start because then it will work I believe...

修改

我更改了一行代码以读取:

I have altered a line of code to read:

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

这现在仅将类添加到第一个要约,而不是第二个要约,然后我尝试重复以下操作:

This now only adds the class to the first offer and not the 2nd offer, I then tried repeating the:

$(this).find()

$(this).find()

围绕初始变量,然后移动:

Around the initial variables and then moved the:

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

但是,在文档准备功能下方的顶部,这停止了任何类的添加.

To the top below the document ready function however, this stopped any class being added.

推荐答案

经过一些重构并与$ this一起使用,我能够使它工作:

After some reconstructing and work with $this I was able to get this working:

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

这篇关于Javascript向Divs添加相同的类,而无需为每个Div计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆