【问题标题】:Javascript: How to add an event listener to the body of a CMS, with the JS code in the headerJavascript:如何将事件侦听器添加到 CMS 的正文中,并在标头中添加 JS 代码
【发布时间】:2015-02-02 08:25:13
【问题描述】:

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

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

我该怎么办?

附带说明,我正在尝试使用纯 JS 来做到这一点。除了一个外部 .js 文件之外,我不想拥有任何东西。所以这意味着没有 jquery 或其他 API,也没有编辑 html。

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

【问题讨论】:

  • 你能发布你目前拥有的javascript吗?有没有理由将它添加到头部而不是身体?为什么不用wordpress的footer方法注入到body底部呢?
  • 是的,马上就来。我希望这一切最终都在一个 .js 文件中,并且完全不显眼。
  • pastebin.com/45FA3fr2 这是标题中的代码。底部函数只是为 window.onload 事件调用多个函数。最上面的函数是问题:var cmarray = document.getElementsByClassName('commentsection'); 似乎返回 null。我认为是因为调用时身体没有加载
  • 整个事情就是你的基本“单击按钮/div”和另一个 div 更改类(css 将其呈现为 display:none;),并且它将按钮的内容更新为“显示或隐藏”。这是一个 jsfiddle 模型:jsfiddle.net/2qt8q2yw

标签: javascript wordpress onclick content-management-system event-listener


【解决方案1】:

理想情况下,您应该将 JS 移动到结束 body 标记之前。如果这不可行,您需要使用文档对象的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.');
};

【讨论】:

  • 但是我使用window.onload加载这两个函数,还是抛出数组为null的错误。
  • 你能显示“数组”为空的示例代码吗?还有你在测试哪个浏览器?
  • Uncaught TypeError: Cannot read property 'addEventListener' of null googling 让我相信这是因为函数运行时 CMS 未加载函数之一找到的
    标记。
  • 您如何检索您正在调用addEventListener 的元素?你能展示整个代码吗?
  • pastebin.com/Ls66r2Au 在这里,它的名称如下:function addcsbuttonlistener(){ document.getElementById("comment-hide-button").addEventListener("click", hidecommentsect); }
猜你喜欢
相关资源
最近更新 更多
热门标签