根据一天中的时间添加课程

问题描述 投票:0回答:2

我正在尝试根据时间将课程添加到#top中。我无法使代码正常工作。

我在这里做错了什么?

      jQuery(document).ready(function(){
            var A = [0,1,6,7,12,13,18,19];
            var B = [2,3,8,9,14,15,20,21];
            var now = new Date();
            var hours = now.getHours();
              if (hours = A) {
                jQuery('#top').addClass('A');
            } else if (hours = B) {
                jQuery('#top').addClass('B');
            } else {
                jQuery('#top').addClass('C');
            }
        });
jquery
2个回答
0
投票

要查找元素是否在数组中,应使用.indexOf()。

例如:如果array.indexOf(something) > -1在数组中,则true返回something

jQuery(document).ready(function(){
            var A = [0,1,6,7,12,13,18,19];
            var B = [2,3,8,9,14,15,20,21];
            var now = new Date();
            var hours = now.getHours();
              if (A.indexOf(hours) > -1) {
                jQuery('#top').addClass('A');
            } else if (B.indexOf(hours) > -1) {
                jQuery('#top').addClass('B');
            } else {
                jQuery('#top').addClass('C');
            }
        });

1
投票

与Evik的答案类似,您可以改用include函数:

jQuery(document).ready(function(){
            var A = [0,1,6,7,12,13,18,19];
            var B = [2,3,8,9,14,15,20,21];
            var now = new Date();
            var hours = now.getHours();
              if (A.includes(hours)) {
                jQuery('#top').addClass('A');
            } else if (B.includes(hours)) {
                jQuery('#top').addClass('B');
            } else {
                jQuery('#top').addClass('C');
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.