我正在尝试编写一个时间戳,打开时为绿色,并在关闭时以黑色字体显示。以下代码似乎应该可以工作。它正确地解析时间,但它没有选择元素。 请看一下:
<style>
.closed-sign {
display: inline;
display: none;
}
</style>
<script>
var myDate = new Date();
var time = 12;
alert(time);
//hour in military
if ((time < 9) || (time >= 17)) {
alert("we are closed");
var openHours = document.getElementById("open");
openHours.classList.add("closed-sign");
var closedHours = document.getElementById('closed');
closedHours.classList.remove("closed-sign");
}
if ((time > 9) && (time <= 17)) {
alert("we are open");
var openHours = document.getElementById("open");
openHours.classList.remove("closed-sign";)
var closedHours = document.getElementById("closed");
closedHours.classList.add("closed-sign");
}
</script>
<div style="float: right;" id="open" class="closed-sign">
<p><span style="color: black">open: </span><span style="color: green;">9:00am - 5pm</span>
</div>
<div style="float: right;" id="closed" class="">
<p><span style="color: black">closed </span>
</div>
&#13;
不应该这样做。我已经尝试了几个甚至循环遍历集合但没有任何工作。我目前放弃尝试按类进行,并尝试按ID选择元素,但由于某种原因我无法添加或删除类。谁能明白为什么?谢谢。
答案 0 :(得分:1)
脚本中存在语法错误 -
closedHours.classList.remove("closed-sign";)
将其更改为 -
closedHours.classList.remove("closed-sign");
在
JavaScript
代码后放置HTML
代码或将JavaScript
代码放入window.onload
活动,如 -
window.onload = function(){
/*Place your all JavaScript code here*/
}
注意:以下是BigUint
答案 1 :(得分:0)
您好,代码中存在语法错误
openHours.classList.remove("closed-sign";)
代码应该是
openHours.classList.remove("closed-sign");
并在html中加载脚本,我改变了脚本的代码。这是100%的工作检查。
<style>
.closed-sign {
display: inline;
display: none;
}
</style>
<div style="float: right;" id="open" class="closed-sign" >
<p><span style="color: black">open: </span><span style="color: green;">9:00am - 5pm</span>
</div>
<div style="float: right;" id="closed" class="" >
<p><span style="color: black">closed </span>
</div>
<script>
var myDate = new Date();
var time = 12;
alert(time);
//hour in military
if ((time <9) || (time >= 17)){
alert("we are closed");
var openHours = document.getElementById("open");
openHours.classList.add("closed-sign");
var closedHours = document.getElementById('closed');
closedHours.classList.remove("closed-sign");
}
if ((time > 9) && (time <= 17)){
alert("we are open");
var openHours = document.getElementById("open");
openHours.classList.remove("closed-sign");
var closedHours = document.getElementById("closed");
closedHours.classList.add("closed-sign");
}
</script>