2012-07-25 41 views
1

我今天有一個問題,當向HTML5 DOM對象添加一個類時。對不起,如果這是一個新手問題。 :P 例如:jQuery:addClass到HTML5 DOM

<!DOCTYPE html> 
<html> 
    <head> 
     <title>stackoverflow example</title> 
     <style> 
     .centercontent { 
      width:100%; 
      max-width:1080px; 
      margin:0 auto; 
     } 
     </style> 
    </head> 
    <body> 
     <header> 
      <!-- All direct children of BODY should be centered on the page; however, children should not be added to .centercontent --> 
      <h1>Site Name</h1> 
     </header> 
     <section> 
      <p>Hello World</p> 
     </section> 
     <footer> 
      &copy; no one 2012 
     </footer> 
    </body> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.j"></script> 
    <script> 
     $("body > *").addClass("centercontent"); 
    </script> 
</html> 

我相信這是我的JS;不過,我從來沒有使用過addClass。非常感謝你的時間。 :) 祝你有美好的一天!

+6

你正在引用jQuery缺少結尾s,它是'src =「http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.j」'但應該是' src =「http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js」' – 2012-07-25 15:02:17

+0

如果你使用瀏覽器開發工具,你可能會像'$未定義' 。 – 2012-07-25 15:06:21

回答

1

您沒有在您的jQuery中使用$(document).ready(function() {...});。試試這個:

$(document).ready(function() { 
    $("body > *").addClass("centercontent"); 
}); 

而且你在你的腳本參考

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.j"></script>  // original 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> // fixed 
+2

由於腳本位於文檔的末尾,因此不需要'$(document).ready()'。 – 2012-07-25 15:04:53

+0

這樣做:D謝謝!編輯:我用cSS – 2012-07-25 15:06:50

+0

@Felix在他的情況下的好處它並不重要!我只是覺得總是這樣做是一種好習慣。 – 2012-07-25 15:08:14

3

寫簡單

body > * { 
    width:100%; 
    max-width:1080px; 
    margin:0 auto; 
} 

在頭部直CSS規則的末尾缺少一個s:期待在你的例子中,jQuery似乎並不是真的需要這個任務。

該選擇器在CSS塊中也是有效的,並且工作正常(不在IE < = 6上)。

+0

+1我同意這是他的場景中的最佳解決方案。 – 2012-07-25 15:05:01