onclick不能与document.getElementsByClassName一起工作

onclick is not working with document.getElementsByClassName

本文关键字:一起 工作 getElementsByClassName document 不能 onclick      更新时间:2023-09-26

我有一个手风琴菜单,用于CMS中的产品描述我正试图开发javascript/css/html,以加快我的数据输入具有相同的类名封装我的节和子节。我在另一个网站上看到了它,觉得它很酷,但我不能让它工作。

E。像这样删除所有部分:

<button class="accordion_f">Section 1 Title</button>
<div class="panel">
 <button class="accordion_f">Section 1 Subsection Title</button>
 <div class="panel">
 Section 1 contents</div>
<button class="accordion_f">Section 2 Title</button>
<div class="panel">
 <button class="accordion_f">Section 2 Subsection Title</button>
 <div class="panel">
 Section 2 contents</div>
 And so on...
Section 1
 Section 1 contents
 Section 1 contents
Section 2 
 Section 2 contents
 Section 2 contents
And so on

这样我就可以剪切和粘贴内容,而不用担心特定的div id名称。

css

    <style>
button.accordion_f {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 14px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}
button.accordion_f.active, button.accordion_f:hover {
    background-color: #ddd;
    color: blue;
}
button.accordion_f:after {
    content: ''02795';
    font-size: 13px;
    color: #777;
    float: right;       
    margin-left: 5px;  
}
button.accordion_f.active:after {
    color: blue;
    content: "'2796";
}
div.panel {
    padding: 0 14px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: 0.3s ease-in-out;
    opacity: 0;
}
div.panel.show {
    opacity: 1;
    max-height: 6000px;  
}
</style> 
JavaScript

<script>
var acc = document.getElementsByClassName("accordion_f");
var i;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
    this.classList.toggle("active");
    this.nextElementSibling.classList.toggle("show");       
    }
}
</script>

当我单独测试它时,它工作正常

如果我将菜单封装在另一个类中,例如在一个药丸菜单中,onclick将不起作用,它不会扩展菜单,css似乎可以工作,背景阴影等,当我检查元素时,我没有看到脚本,是影响文档的父类。getElementsByClassName如何?

<ul class="tabs">
<button class="accordion_f">Section 1</button>
<div class="panel">
<p>Offers an easy way to connect your Polar training device with 3<sup>rd</sup> party services.</p>
</div>
</ul>

Onclick not firing…

我用各种索引号手动扩展菜单来测试我的菜单:

acc[0].classList.toggle("active");
acc[0].nextElementSibling.classList.toggle("show");

这个工作,所以我很困惑为什么onclick不工作。

请帮。

它正在工作,即在兼容模式下,ie8对文档的支持很差。getElementsByClassName