首页 > 解决方案 > 表中的简单手风琴js问题

问题描述

我在我的 WP 站点中添加了一个表格插件的代码片段,它应该在表格的每个产品行下添加一个手风琴,单击时将显示更多信息。

第一个手风琴正在正常工作,但是每个产品行下的所有其他手风琴在单击时都没有响应。

我怎样才能解决这个问题?

<script>
var i;
var acc = document.getElementsByClassName("accordion");
for (i = 0; i < acc.length; i++) {  
    acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "table-row") {
      panel.style.display = "none";
    } else {
      panel.style.display = "table-row";
    }
  });
}
</script>


<tr class="accordion">
<td colspan="100">Find out more about
     <?php global $product;
            echo $product->get_short_description();
      ?>
</td>
</tr>

<tr class="panel">
<td colspan="100">    
      <?php global $product;
            echo $product->get_description();
      ?>

</td>
</tr>

片段更新(似乎工作见评论)

var i;
var acc = document.getElementsByClassName("accordion");
for (i = 0; i < acc.length; i++) {  
    acc[i].addEventListener("click", function() {
    /* this.classList.toggle("active") */;
    var panel = this.nextElementSibling;
    
    if (panel.style.display === "table-row") {
      panel.style.display = "none";
    } else {
      panel.style.display = "table-row";
    }
      });
}
<table>
<tr class="accordion">
<td>Find out more about 1
     
</td>
</tr>

<tr class="panel">
<td>    
      Panel 1

</td>
</tr>

<tr class="accordion">
<td>Find out more about 2
     
</td>
</tr>

<tr class="panel">
<td>    
      Panel 2

</td>
</tr>

<tr class="accordion">
<td>Find out more about 3
     
</td>
</tr>

<tr class="panel">
<td>    
      Panel 3

</td>
</tr>
</table>

标签: javascripthtmlaccordion

解决方案


推荐阅读