将CSS类添加到div

时间:2011-11-27 04:11:37

标签: javascript

我写了这个脚本,但它只有在我没有广告class="yes"的情况下才有效,但是如果我添加它,它将无效,这是什么原因。谢谢。

这有效:

<script type="text/javascript">  

    var d=new Date();
    var weekday=new Array(7);
    weekday[0]="<div>Sunday</div>";
    weekday[1]="<div>Monday</div>";
    weekday[2]="<div>Tuesday</div>";
    weekday[3]="<div>Wednesday</div>";
    weekday[4]="<div>Thursday</div>";
    weekday[5]="<div>Friday</div>";
    weekday[6]="<div>Saturday</div>";

    document.write("Today is " + weekday[d.getDay()]);

</script>

这不起作用

<script type="text/javascript">

    var d=new Date();
    var weekday=new Array(7);
    weekday[0]="<div class="yes">Sunday</div>";
    weekday[1]="<div class="yes">Monday</div>";
    weekday[2]="<div class="yes">Tuesday</div>";
    weekday[3]="<div class="yes">Wednesday</div>";
    weekday[4]="<div class="yes">Thursday</div>";
    weekday[5]="<div class="yes">Friday</div>";
    weekday[6]="<div class="yes">Saturday</div>";

    document.write("Today is " + weekday[d.getDay()]);

 </script>

4 个答案:

答案 0 :(得分:4)

尝试单引号:

<script type="text/javascript">

    var d=new Date();
    var weekday=new Array(7);
    weekday[0]="<div class='yes'>Sunday</div>";
    weekday[1]="<div class='yes'>Monday</div>";
    weekday[2]="<div class='yes'>Tuesday</div>";
    weekday[3]="<div class='yes'>Wednesday</div>";
    weekday[4]="<div class='yes'>Thursday</div>";
    weekday[5]="<div class='yes'>Friday</div>";
    weekday[6]="<div class='yes'>Saturday</div>";

    document.write("Today is " + weekday[d.getDay()]);

 </script>

答案 1 :(得分:3)

请注意语法高亮 - 您的双引号与字符串的开头和结尾双引号相匹配。你需要逃脱它们:

<script type="text/javascript">

    var d = new Date();
    var weekday = new Array(7);
    weekday[0] = "<div class=\"yes\">Sunday</div>";
    weekday[1] = "<div class=\"yes\">Monday</div>";
    weekday[2] = "<div class=\"yes\">Tuesday</div>";
    weekday[3] = "<div class=\"yes\">Wednesday</div>";
    weekday[4] = "<div class=\"yes\">Thursday</div>";
    weekday[5] = "<div class=\"yes\">Friday</div>";
    weekday[6] = "<div class=\"yes\">Saturday</div>";

    document.write("Today is " + weekday[d.getDay()]);

</script>

哦,这可能更简单:

<script type="text/javascript">
    document.write("Today is <div class=\"yes\">" +
        ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"][new Date().getDay()] +
        "day</div>");
</script>

答案 2 :(得分:2)

你的双引号打破了字符串。变化

weekday[0]="<div class="yes">Sunday</div>";

weekday[0]="<div class='yes'>Sunday</div>";

答案 3 :(得分:2)

您需要使用单引号:

weekday[0]="<div class='yes'>Sunday</div>";

如果你不这样做,你的String将无效,因为接受的第一个字符串将是

"<div class=" 

然后其他人不会被期待。