javascript - 手风琴按钮不会在 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 的链接,因为我可以在源代码中看到它。
解决方案
尝试像这样将您的脚本排入队列:
wp_enqueue_script( 'accordion js', get_stylesheet_directory_uri() . '/js/accordion.js', array(), null, true);
它确保脚本在页面加载后加载,并且可以找到您在页面上定位的元素,即.accordion
推荐阅读
- c# - 在没有数组或任何循环的情况下从用户那里获取 5 个值并找到最大值和最小值
- azure - 天蓝色。手动触发时释放未触发并卡住
- python - TensorFlow Serving:在运行时更新 model_config(添加其他模型)
- python - 如何按值解析 argparser 参数
- magento2 - Magento2 您必须使用 --with-jpeg-dir=DIR 选项安装 GD 库
- pandoc - pandoc-crossref 不在 MS Word 中显示图形/方程式编号
- python - 如何在networkx中找到一个图的所有连接子图?
- mysql - “以下查询失败”错误执行存储的例程
- node.js - 使用 Node.js 设置内部 Web 服务器
- r - 卡方模拟错误 - 无法分配大小为 134217728 Tb 的内存块