2011-11-27 212 views
1

我編寫了這個腳本,但它只適用於我沒有廣告class="yes",但如果iI添加它,它不會工作,這是什麼原因。謝謝。

這工作:將CSS類添加到div

<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

嘗試單引號:

<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> 
2

你的雙引號是打破字符串。更改

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

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

你需要使用單引號:

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

如果你不這樣做,你的字符串將是無效的,因爲第一個String接受將是

"<div class=" 

然後t他休息不會被期望。

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>