首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >某些JavaScript不能在WordPress上加载

某些JavaScript不能在WordPress上加载
EN

Stack Overflow用户
提问于 2018-08-05 05:57:35
回答 1查看 54关注 0票数 0

我在解决WordPress站点上的JavaScript折叠菜单问题时遇到了问题。当单击accordion按钮时,它不会显示隐藏在它下面的内容。我尝试了许多解决方案,它们要么不起作用,要么超出了我的能力范围。我是一个初学者,这可能是一个简单的修复方法,但我已经在这个问题上挣扎了几天。下面是我的代码:

JavaScript:

代码语言:javascript
复制
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";
        }
    });
}

CSS:

代码语言:javascript
复制
/* Style the buttons that are used to open and close the accordion panel */
.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    text-align: left;
    border: none;
    outline: none;
    transition: 0.4s;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.active, .accordion:hover {
    background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */
.panel {
    padding: 0 18px;
    background-color: white;
    display: none;
    overflow: hidden;
} 

HTML:

代码语言:javascript
复制
<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>

根据FireFox的说法,令人不快的代码片段是if (panel.style.display === "block") {,它抛出一个TypeError: panel is null异常。我已经用alert('hi');测试了我的页面,它工作得很好,所以我认为JavaScript正在加载。

EN

回答 1

Stack Overflow用户

发布于 2018-08-05 08:25:48

我将你的代码添加到一个jsfiddle中,它似乎工作得很好,两个按钮都显示了隐藏的内容。

https://jsfiddle.net/pnuyLhbq/1/

因此,如果添加另一个折叠按钮,当前代码就没问题了

代码语言:javascript
复制
<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51689828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档