首页 > 解决方案 > 手风琴按钮不会在 WordPress 中切换

问题描述

我在获取用于手风琴样式按钮的简单 JavaScript 时遇到问题。我直接从这个例子中复制了代码。我遵循了视频教程第 1部分和第 2部分,以及在 WordPress Codex 上使用 JavaScript 。

这是手风琴.js

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function() {
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    });
}

这是functions.php

<?php
function my_theme_enqueue_styles() {

    $parent_style = 'hestia-style'; // This is 'hestia-style' for the Hestia theme.

    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

<?php
function hestia_child_scripts() {
    wp_enqueue_script( 'accordion js', get_stylesheet_directory_uri() . '/js/accordion.js');
}
add_action( 'wp_enqueue_scripts', 'hestia_child_scripts' );
?>

这是我的 HTML

<button class="accordion">Are there minimums?</button>
<div class="panel">
   <p>We accept orders of any size.</p>
</div>

正在生成手风琴.js 的链接,因为我可以在源代码中看到它。

标签: javascriptphphtmlcsswordpress

解决方案


尝试像这样将您的脚本排入队列:

wp_enqueue_script( 'accordion js', get_stylesheet_directory_uri() . '/js/accordion.js', array(), null, true);

它确保脚本在页面加载后加载,并且可以找到您在页面上定位的元素,即.accordion


推荐阅读