某些JavaScript无法在WordPress上加载

时间:2018-08-04 21:57:35

标签: javascript html css wordpress

我在解决WordPress网站上的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:

/* 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:

<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正在加载。

1 个答案:

答案 0 :(得分:0)

我将您的代码添加到jsfiddle中,并且看起来工作正常,两个按钮都显示了隐藏的内容。

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

因此,如果您添加另一个手风琴按钮

<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>