我正在尝试根据时间将课程添加到#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');
}
});
要查找元素是否在数组中,应使用.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');
}
});
与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');
}
});