純粋なjavaScriptでアコーディオンのコンストラクタ関数を作成しようとしていますが、動作しません... "this"というキーワードに何か関係があると思います..私は通常の関数でコードを書いていますそれは動作しましたが、以下のコンストラクタでは動作しませんでした。純粋なJavaScriptを使用してアコーディオンコンストラクタ関数を作成する方法は?
function Accordion(accordionId) {
this.container = document.getElementById(accordionId);
this.headers = this.container.getElementsByClassName("accordion-header");
this.sections = this.container.getElementsByClassName("accordion-section");
for (var i = 0; i < this.headers.length; i++) {
this.headers[i].addEventListener("click", this.toggleSections);
}
this.toggleSections = function() {
var toggeld = this.nextElementSibling.className;
for (var i = 0; i < this.sections.length; i++) {
this.sections[i].className = "accordion-section";
}
if (toggeld === "accordion-section") {
this.nextElementSibling.className = "accordion-section-displayed";
} else {
this.nextElementSibling.className = "accordion-section";
}
}
}
var newAccordion = new Accordion("accordion-wrapper");
<div id="accordion-wrapper">
<h3 class="accordion-header">First Section</h3>
<div class="accordion-section">
.
</div>
<h3 class="accordion-header">Second Section</h3>
<div class="accordion-section">
</div>
<h3 class="accordion-header">Third Section</h3>
<div class="accordion-section">
</div>
</div>
クリックイベントでは「this.sections」は利用できません – mplungjan
ご返信ありがとうございます。それは役に立ちました。 –