无法在 HTMLButtonElement 处读取 属性 'style' 的 null

Cannot read property 'style' of null at HTMLButtonElement

我的 Javascript 没有加载说在我的 javascript if (panel.style.maxHeight) 的第 9 行“无法读取 属性 'style' of null at HTMLButtonElement."

这是我的 HTML:

<p><button class="accordion">Section 1</button></p>
<div class="panel">
<p>Lorem ipsum...</p>
</div>

<p><button class="accordion">Section 2</button></p>
<div class="panel">
<p>Lorem ipsum...</p>
</div>

<p><button class="accordion">Section 3</button></p>
<div class="panel">
<p>Lorem ipsum...</p>
</div>

这是我对应的 JavaScript:

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

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}

检查面板兄弟是否存在,并将手风琴放在与面板相同的级别。

删除了按钮周围的段落包装以演示功能

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

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (!panel) return;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}
<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>

<p><button class="accordion">Section 2</button></p>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>

<p><button class="accordion">Section 3</button></p>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>