避免內聯JavaScript有很多原因,其中最重要的可能是代碼可維護性。
一個簡單的例子(我只是為了演示目的使用jQuery)。
<p class="element" onclick="doSomething();">Click me</p><p class="element" onclick="doSomething();">Click me</p>
<p class="element" onclick="doSomething();">Click me</p><p class="element" onclick="doSomething();">Click me</p>
<p class="element" onclick="doSomething();">Click me</p><p class="element" onclick="doSomething();">Click me</p>
如果突然收到一個請求,要求更改所有段落以執行另一項功能,該怎么辦?在您的示例中,您必須手動更改HTML代碼中的所有內容。但是,如果您選擇將HTML與JavaScript分離,您可以這樣做。
<p class="element">Click me</p><p class="element">Click me</p><p class="element">Click me</p><p class="element">Click me</p>
<p class="element">Click me</p><p class="element">Click me</p>$('.element').bind('click', doSomethingElse);
HTML代碼也更干凈,這使得設計者可以完全專注于設計,而不必擔心他們在做一個也涉及到其他人的項目時可能會破壞一些東西。
編輯:為我的評論舉個例子。
Project = {
// All the variables/constants/objects that need to be globally accessible inside the Project object.
init : function(){
// Main entry point...
this.MainMenu.init();
// Rest of the code which should execute the moment Project is initiated.
}}Project.MainMenu = {
// All the variables/constants/objects that need to be accessible only to MainMenu.
init : function(){ // Is run immediatelly by Project.init()
// Event handlers relevant to the main menu are bound here
// Rest of the initialization code
}}Project.SlideShow = {
// All the variables/constants/objects that need to be accessible only to SlideShow.
init : function(){ // Is run only on pages that really require it.
// Event handlers for the slideshow.
}}