基于currentTime更改类属性

时间:2012-07-12 09:29:09

标签: javascript html class variables time

所以,我有一些代码,由于一些奇怪的原因不起作用。任务是更改ID为class IF 的元素的属性blogtxtday变量等于4,5或6 (周五,周六,周日) 我还希望在hours使用day = 4 &&变量。 另外,我确定问题不在 IF 语句中,因为代码甚至不会执行alert(currentTime)

  

问:上面的代码有什么问题?

<script>
var currentTime = new Date()
var day = currentTime.getDay()
var hours = currentTime.getHours()
alert(currentTime)
if (day = 4 && || day = 5 || day = 6) {
    document.getElementById("blogtxt").setAttribute("class", "friss");
    else document.getElementById("blogtxt").setAttribute("class", "");
}
</script>

4 个答案:

答案 0 :(得分:2)

if (day = 4 && || day = 5 || day = 6) {
    document.getElementById("blogtxt").setAttribute("class", "friss");
    else document.getElementById("blogtxt").setAttribute("class", "");
}

应该是:

if (day == 4 || day == 5 || day == 6) {
    document.getElementById("blogtxt").setAttribute("class", "friss");
} else {
    document.getElementById("blogtxt").setAttribute("class", "");
}

答案 1 :(得分:2)

您遇到了一堆错误,JSLint会检测到错误:

day = 4应为day == 4。 if子句中有一个无关的&&。 你没有为then子句使用紧支撑,或者使用else子句的开括号。

更正了http://jsfiddle.net/barmar/7nRXG/

的代码

答案 2 :(得分:1)

这里有语法错误,这就是代码甚至无法执行的原因:

if (day = 4 && || day = 5 || day = 6)

您无法编写&& ||,请将其替换为:

if (day === 4 || day === 5 || day === 6)

else也存在语法错误,该错误应为:

if (day === 4 || day === 5 || day === 6) {
    document.getElementById("blogtxt").setAttribute("class", "friss");
} else {
    document.getElementById("blogtxt").setAttribute("class", "");
}

答案 3 :(得分:0)

给予;完成声明。 //“;”是语句终止符。 像这样修改代码:

<script>
var currentTime = new Date();
var day = currentTime.getDay();
var hours = currentTime.getHours();
alert(currentTime);
if (day = 4 && || day = 5 || day = 6){
 document.getElementById("blogtxt").setAttribute("class", "friss");
else
 document.getElementById("blogtxt").setAttribute("class", "");}
</script>

希望这会有所帮助。

你也不能使用&& || ..这是语法错误。将其替换为||

花括号({})在if-else语句中也没有正确完成。

并且if语句比较运算符为==而不是=

相关问题