在Java中满足所有条件时显示块

时间:2018-08-16 21:48:44

标签: javascript jquery

如果符合以下条件,我有一个要显示的块:

  • 不是周末
  • 不是银行假日(循环浏览一系列银行假日日期
  • 在定义的开始时间和结束时间之外

我认为这接近工作。当针对每个条件进行测试时,我可以使交换工作,但是我认为,当尝试对所有条件进行测试时,我的代码/条件似乎有些混乱。

在这里,我非常感谢您能帮上忙-在所有条件为真时显示,而在假条件下不显示:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
(function () {

//set current date
var currentDate = new Date();

//bank holidays
var bank1 = { year: 2018, month: 9, day: 3 } ;
var bank2 = { year: 2018, month: 10, day: 14 } ;
var bank3 = { year: 2018, month: 11, day: 12 } ;
var bank4 = { year: 2018, month: 12, day: 10 } ;

//declare time variables
var startTime = { hour: 9, minute: 30 } ;
var endTime = { hour: 16, minute: 30 } ;

//set bank holidays in array
var bankholidays = [new Date(bank1.year, bank1.month - 1, bank1.day), new Date(bank2.year, bank2.month - 1, bank2.day), new Date(bank3.year, bank3.month - 1, bank3.day), new Date(bank4.year, bank4.month - 1, bank4.day)];

//set start and finish time
var starterTime = new Date(startTime.hour, startTime.minute);
var finisherTime = new Date(endTime.hour, endTime.minute);

//get current time
var myCurrentTime = new Date(currentDate.getHours(), currentDate.getMinutes());

//include logic for time in variable
var time = starterTime.getTime() <= myCurrentTime.getTime() && myCurrentTime.getTime() < finisherTime.getTime();

//get current date
var myCurrentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());

//set variable to store criteria when it's not a weekend
var notWeekend = currentDate.getDay() != 6 && currentDate.getDay() != 0;

//set logic to show block if it's not a bank holiday, if it's between 9.30 and 4.30 and it's weekday. Otherwise the block will show
if(time && notWeekend)

{

    $(".block").show();

}

else

{

//loop through array of bank holidays and compare each against and check if any are a bank holiday and display block if it is a bank holiday
    for (i = 0; i < bankholidays.length; i++) 

    {

        if(bankholidays[i].getTime() == myCurrentDate.getTime())

        { 

            $(".block").show();

        }

        else

        {

            $(".block").hide();

        }

    }

}

})();
</script>
</head>
<body>

<p class = "block">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>

</body>
</html> 

4 个答案:

答案 0 :(得分:0)

我帮你清理了。主要部分是向其添加$(document).ready,否则它将根本无法运行。

必须清理它,以确保逻辑按照预期的方式工作。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {

//set current date
var currentDate = new Date();

//bank holidays
var bank1 = { year: 2018, month: 9, day: 3 } ;
var bank2 = { year: 2018, month: 10, day: 14 } ;
var bank3 = { year: 2018, month: 11, day: 12 } ;
var bank4 = { year: 2018, month: 12, day: 10 } ;

//declare time variables
var startTime = { hour: 9, minute: 30 } ;
var endTime = { hour: 16, minute: 30 } ;

//set bank holidays in array
var bankholidays = [new Date(bank1.year, bank1.month - 1, bank1.day), new Date(bank2.year, bank2.month - 1, bank2.day), new Date(bank3.year, bank3.month - 1, bank3.day), new Date(bank4.year, bank4.month - 1, bank4.day)];

//set start and finish time
var starterTime = new Date(startTime.hour, startTime.minute);
var finisherTime = new Date(endTime.hour, endTime.minute);

//get current time
var myCurrentTime = new Date(currentDate.getHours(), currentDate.getMinutes());

//include logic for time in variable
var time = starterTime.getTime() <= myCurrentTime.getTime() && myCurrentTime.getTime() < finisherTime.getTime();

//get current date
var myCurrentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());

//set variable to store criteria when it's not a weekend
var notWeekend = currentDate.getDay() != 6 && currentDate.getDay() != 0;

//set logic to show block if it's not a bank holiday, if it's between 9.30 and 4.30 and it's weekday. Otherwise the block will show
if(!time || !notWeekend)
{
    $(".block").hide();
}

//loop through array of bank holidays and compare each against and check if any are a bank holiday and display block if it is a bank holiday
for (i = 0; i < bankholidays.length; i++) 
{
    if(bankholidays[i].getTime() == myCurrentDate.getTime())

    { 
         $(".block").show();
    }
}


})();
</script>
</head>
<body>

<p class = "block">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>

</body>
</html> 

由于默认情况下该文本是可见的,因此您只需将其隐藏即可。这将消除else子句。因此,您要做的是代替检查它们是否使检查巫婆使其可见。您检查他们是否不进行检查并隐藏它们。

答案 1 :(得分:0)

这有点混乱,因为它没有分为功能。 创建一个名为“ validateDateAndTime(date)”的函数或类似的函数。 它将执行以下操作:

return notWeekend(date) && notHoliday(date) && inWorkingHours(date)

然后创建一个函数来切换您的块(通常,缓存querys元素以避免多个DOM查询)。它会变成true / false,并相应地显示/隐藏。 然后您需要做的所有事情:

toggleBlock(validateDateAndTime(date));

很难说出哪种架构最适合您,但这肯定会使代码更具可读性。

答案 2 :(得分:0)

尝试这样的事情:

var bankHoliday = function (date) {
    for (var i = 0; i < bankholidays.length; i++) {
        if (bankholidays[i].getTime() === date.getTime()) {
            return true
        }
    }
    return false;
};

if (time && notWeekend && !bankHoliday(myCurrentDate)) {
    $(".block").show();
}
else {
    $(".block").hide();
}

答案 3 :(得分:0)

好的,因此您的代码存在多个问题,而且混乱不堪,这使您更难弄清实际发生了什么。我继续清理您的代码,并尽力在每行上添加注释,以解释其功能。

需要注意的关键一点是,我将所有代码移动到了一个命名空间,并附加到ready事件中,并在该事件中调用我的函数。这对于代码正常运行不是必需的,但是可以将代码与可能受到污染的区域隔离开来,并且可以轻松地在以后的代码中引用。

// create a namespace for your application
var myApp = new (function(){

	// store a reference to this instance to reference later, use a constant for this
	const self = this;
  
  // store the bank holiays as actual dates in an array,
  // just do the math here for the 0 based index of months
  let bankHolidays = [
  	new Date(2018, 8, 3),
    new Date(2018, 9, 14),
    new Date(2018, 10, 12),
    new Date(2018, 11, 10)
  ];
  
  // just store the bank hours as dates but disregard the date and 
  // just use the time later
  let bankHours = {
  	open: new Date(1999, 0, 1, 9, 30),
    close: new Date(1999, 0, 1, 16, 30)
  }
  
  // This is a simple function to check if the times of a given date is
  // between the times of two other dates
  self.isTimeBetween = function(testDate, startDate, endDate){
  	// construct a new date and time using testDate for the day info 
    // and the start and end dates for the times
  	let startTime = new Date(testDate.getFullYear(), 
    												 testDate.getMonth(), 
                             testDate.getDate(),
                             startDate.getHours(),
                             startDate.getMinutes());
                             
    let endTime = new Date(testDate.getFullYear(), 
    												 testDate.getMonth(), 
                             testDate.getDate(),
                             endDate.getHours(),
                             endDate.getMinutes()); 
                             
    // getTime returns the number of milliseconds since January 1, 1970, 00:00:00
    // we can use this to see if testDate is between start and end
  	return testDate.getTime() >= startTime.getTime() && 
    			testDate.getTime() <= endTime.getTime();
  }
  
  // expose the function to call and set your UI
  self.toggleData = function(){
    // get the current date and time, just create a new Date will get that for you
    let today = new Date();
    // check if its a weekend
    let isWeekend = today.getDay() == 6 && today.getDay() == 0;
    // check if we are inbetween the open hours
    let isOpen = self.isTimeBetween(today, bankHours.open, bankHours.close);
  	// check if its a holiday, use Array.some to test all the
    // holidays we stored earlier. 
    let isHoliday = bankHolidays.some(function(item){
    	return item.getDate() == today.getDate() &&
      			 item.getMonth() == today.getMonth() && 
             item.getFullYear() == today.getFullYear()
    });
    
    // check if we need to show the block
    if (!isWeekend && !isHoliday && isOpen)
    	$(".block").show();
    else
      $(".block").hide();
  }
})();

// attach to the ready function and execute your function
$(document).ready(function() { 
	// call my function inside the namespace I created
  myApp.toggleData();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="block">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
  software like Aldus PageMaker including versions of Lorem Ipsum.
</p>