javascript - 页脚中有functions.php 脚本。不是头

标签 javascript php wordpress

我有一个 JS 文件,其中包含许多可用于 DOM 操作的函数。我添加了来自 W3 学校的悬停事件监听器,并收到“无法读取 null 属性“addEventListener””错误。

  let hover = document.querySelectorAll(".center-nav a");


  hover.addEventListener("mouseenter", function( event ) {   
    // highlight the mouseenter target
    event.target.style.color = "purple";

    // reset the color after a short delay
    setTimeout(function() {
      event.target.style.color = "";
    }, 500);
  }, false);

做了一些挖掘并阅读了它,因为此事件是在页面 HTML 之前加载的。这是有道理的,因为 main.js 文件位于头部。

我的functions.php

function mikes_files(){
    wp_enqueue_style('main-style', get_stylesheet_uri(), NULL, microtime() );
    wp_enqueue_script( 'prefix-font-awesome', 'https://kit.fontawesome.com/xxxxx.js' );  
    wp_enqueue_script('main-js', get_template_directory_uri() . '/main.js', NULL, microtime() );
}



add_action('wp_enqueue_scripts', 'mikes_files', 999);

了解到 999 有助于使其最后加载,但它仍然在头脑中。

我是否可以使用代码创建一个不同的 js 文件并找到将其放入页脚所需的函数?

最佳答案

更改此行:

wp_enqueue_script('main-js', get_template_directory_uri() . '/main.js', NULL, microtime() );

这样:

wp_enqueue_script('main-js', get_template_directory_uri() . '/main.js', array(), microtime(), true );

wp_enqueue_script <head>中有一个选项可以定义是否加载脚本或之前</body> 。默认wp_enqueue_script加载 <head> 中的脚本只需将第五个参数传递给 true</body>之前加载它。更多详情请引用wp_enqueue_script文档。

此外,querySelectorAll返回 NodeList 并且不能调用addEventListener使用节点列表。您应该迭代 NodeList,并应用 addEventListener到每个元素。

关于javascript - 页脚中有functions.php 脚本。不是头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59311760/

相关文章:

javascript - Facebook Connect 按钮问题 - 请帮忙

javascript - 如何更改 Leaflet 1.0.3 中 LineStrings 的 geoJSON 层的样式

javascript - 流提示对象默认值解构中的不兼容类型

php - 从两个表中检索信息

javascript - Uncaught ReferenceError : google is not defined (Wordpress)

php - 如何在模板/函数中显示 WordPress WooCommerce 自定义属性?

javascript - EXtjs 网格过滤器

php - 登录时如何处理不同类型的用户?

php - Laravel 5 使用关系查询导致 "Call to a member function addEagerConstraints() on null"错误

wordpress - Bulma "is-marginless"类不删除容器组件上的 "margin-right"