使用 JS 切换 类 中的元素

Toggle elements from classes with JS

我想在有人点击显示更多按钮时显示更多信息。复杂的是有几个按钮和信息可以用相同的类名切换。 我做错了什么??

var element = document.querySelectorAll("btn");
for (var i = 0; i < button_length ; i++) {
   element[i].addEventListener("click", function() {
   alert("Button Clicked " + i);
   element[i].classList.toggle("extrainfo");
};
}
 td{border:solid 1px black;}
 .btn, #btn_id{color:blue; text-decoration:underline; cursor:pointer;}
 
.extrainfo{
  display:none
}
<table>

  <tbody>
    <tr class="info_group">
      <td>Title 1</td>
      <td class="btn">show more</td>
    </tr>
    <tr>
      <td class="extrainfo" colspan="2">More info 1</td>
    </tr>
   </tbody>
   
     <tbody>
    <tr class="info_group">
      <td>Title 2</td>
      <td class="btn">show more</td>
    </tr>
    <tr>
      <td class="extrainfo" colspan="2">More info 2</td>
    </tr>
   </tbody>
   
     <tbody>
    <tr class="info_group">
      <td>Title 3</td>
      <td class="btn">show more</td>
    </tr>
    <tr>
      <td class="extrainfo" colspan="2">More info 3</td>
    </tr>
   </tbody>
  
</table>

为你工作javaScript

var element = document.querySelectorAll("btn"); // need to be (".btn")

// you want it to be i < element.length; ? or there's a variable called button_length?
for (var i = 0; i < button_length ; i++) { 
       element[i].addEventListener("click", function() {
       alert("Button Clicked " + i);
       element[i].classList.toggle("extrainfo");
    }; // missing a Parenthesis need to be this }); not this };
    }

我仍然不确定该功能,但如果这正是您要查找的内容,请参阅下面的代码。

var element = document.querySelectorAll(".btn");
var extraInfo = document.querySelectorAll(".extrainfo");

for (let i = 0; i < element.length; i++) {
   element[i].addEventListener("click" , function() {
   extraInfo[i].classList.toggle("extrainfo");
   });
}

hereJSFiddle 你可以玩玩代码