[英]Some JavaScript will not load on 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');
測試了我的頁面alert('hi');
,效果很好,因此我認為JavaScript正在加載。
我將您的代碼添加到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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.