2010-12-01 64 views
2

有點新來jQuery和尋找幫助如何將所有我的腳本保存在一個外部文件中,而不是全部嵌套在document.ready();.我希望只能從特定頁面調用某些函數,其餘部分則使用ready();來處理。我不是100%確定從頁面調用函數的最佳做法是什麼:/ 謝謝。調用外部jQuery函數w/o document.ready();

+0

我不確定你的意思。當DOM準備就緒時,你可以做任何事情。和? – karim79 2010-12-01 01:24:00

回答

2

有多個document.readys沒有錯誤

我喜歡爲每個頁面添加一個唯一的ID,並且在執行前檢查該ID是否存在。您可以創建一個簡單的包裝功能,做檢查和的document.ready等待:

var pageReady = function (id, callback) { 
    $(function() { 
     if ($(id).length) { 
     callback(); 
     } 
    }); 
}; 

隨後,類似的document.ready,你可以有:

pageReady("#home-page", function() { 
    // Code will only run for home page here 
}); 

pageReady("#search-page", function() { 
    // Code will only run for search page here 
}); 

記得剛加入的ID ...

<body id="home-page"> 
0

您可以使用多個dom readys。

我最喜歡的方式來確定是否在一個頁面是給身體各式獨特的I類應該運行一些代碼,然後用這個...

if ($('body').hasClass('contact')) { 
    // Validate form, etc 
} 
0

雖然JavaScript提供加載事件在呈現頁面時執行代碼,直到所有資源(如圖像)都已完全接收後纔會觸發此事件。在大多數情況下,腳本可以在DOM層次結構完全構建後立即運行。傳遞給.ready()的處理程序保證在DOM準備就緒後執行,因此這通常是附加所有其他事件處理程序並運行其他jQuery代碼的最佳位置。在使用依賴CSS樣式屬性值的腳本時,在引用腳本之前引用外部樣式表或嵌入樣式元素很重要。

http://api.jquery.com/ready/

0

在外部文件中,可以有$(document).ready(function() { //code here; });另外,你可以把所有的功能在外部文件,然後只需您的網頁上已經

$(document).ready(function() { myfunction(); }); 
+0

Aww,感謝編輯 – Prescott 2010-12-01 01:52:19

2

你可以把你的所有如果你喜歡,可以在單個文件中使用腳本如果您不需要操作DOM或與DOM進行交互,那麼您可以在文件中使用普通的JS函數,而不使用document.ready()函數。然後,您可以將所有DOM操作和交互JS放入document.ready()函數中。您還可以將JS放入$(window).load()函數中,以便在所有資源加載到包含圖像的頁面上後運行代碼。

例子:

$(window).load(function() { 
    // code that will run once all resources and the DOM are loaded into the browser 
    console.log("window loaded"); 
}); 

runOnScriptLoad(); 
function runOnScriptLoad() { 
    // code that will run as soon as the JS file loads 
    console.log("script loaded"); 
} 

$(document).ready(function() { 
    // code that will run once the entire DOM is loaded into the browser 
    console.log("DOM ready"); 
}); 

$(window).load(function() { 
    // code that will run once all resources and the DOM are loaded into the browser 
    console.log("window loaded"); 
}); 

示例頁面: =>http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-dom-ready.html

讓你的螢火控制檯時打開加載頁面,你會看到在每一個得到執行的順序。

+0

+1,我喜歡用`$(窗口)。load()` – Alex 2010-12-01 02:05:19

+0

@Alex爲什麼?只有特定的情況下這是有用的,因爲它比文檔準備好慢。 – 2010-12-01 04:11:03