Javascript:如何将事件侦听器添加到CMS的主体中,JS代码在标头中

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

本文关键字:主体 JS 代码 CMS 事件 添加 侦听器 Javascript      更新时间:2023-09-26

我编写了一个脚本,将侦听器添加到 onClick 事件中。 单击时,它会在文档中搜索具有特定类"someclass"的任何元素,然后对其执行一些操作等。

问题是,在找到所有带有class="someclass"的元素

后,class="someclass"的所有元素的数组都是空的。 我认为这是因为添加侦听器的 JS 代码位于标头中,当它运行时,包含实际的正文(来自与 CMS 不同的 php 文件)尚未加载。

我该怎么办?

旁注,我正在尝试使用纯JS来执行此操作。 我不想有一个外部.js文件以外的任何东西。 所以这意味着没有jquery或其他API,也没有编辑html。

我在这里有什么选择? 感谢您的阅读。

理想情况下,您应该将JS移到结束正文标签之前。如果无法做到这一点,则需要使用文档对象的 DOMContentLoaded 事件或窗口对象的 load 事件。

您的问题是页面的 DOM 尚未准备就绪,因此您的 JS 代码还没有要访问的内容。更多信息在这里:

  • https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
  • https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload

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.');
};