簡體   English   中英

Javascript:如何將事件偵聽器添加到CMS正文中,並在標頭中添加JS代碼

[英]Javascript: How to add an event listener to the body of a CMS, with the JS code in the header

我編寫了一個腳本,為onClick事件添加了一個偵聽器。 單擊后,它將在文檔中搜索具有特定類“ someclass”的任何元素,然后對其進行一些操作等。

問題是,在找到所有具有class =“ someclass”的元素之后,所有具有class =“ someclass”的元素的數組為空。 我認為這是因為添加偵聽器的JS代碼位於標頭中,並且在其運行時,尚未加載包含實際內容的正文(來自CMS的其他php文件)。

我該怎么辦?

附帶說明,我正在嘗試使用純JS執行此操作。 除了一個外部.js文件之外,我不想有任何其他東西。 因此,這意味着沒有jquery或其他API,也無需編輯html。

我在這里有什么選擇? 感謝您的閱讀。

理想情況下,您應該將JS移到結束標記之前。 如果不可能,則需要使用文檔對象的DOMContentLoaded事件或窗口對象的load事件。

您的問題是頁面的DOM尚未准備就緒,因此您的JS代碼尚無任何訪問權限。 更多信息在這里:

DOMContentLoaded可在現代瀏覽器和IE9 +中使用 ):

document.addEventListener('DOMContentLoaded', function(event) {
  console.log('DOM fully loaded and parsed');
});

加載適用於所有瀏覽器 ):

window.onload = function() {
  console.log('The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.');
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM