在页脚中具有functions.php脚本。不是头

问题描述 投票:0回答:2

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

  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文件,并找到了将其放在页脚中所需的功能?

javascript php wordpress
2个回答
0
投票

如果使用的是/可以使用jQuery,则只需将函数包装在$(document).ready(function(){ **your code**});中。如果您使用的是香草JS,请查看Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it


0
投票

更改此行:

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>中的脚本,只需将第5个参数传递给true即可在</body>之前加载脚本。有关更多详细信息,请参阅wp_enqueue_script文档。

此外,querySelectorAll返回NodeList,并且您不能使用NodeList调用addEventListener。您应该遍历NodeList,并将addEventListener应用于每个元素。

© www.soinside.com 2019 - 2024. All rights reserved.