首页 > 解决方案 > 在同一个“按钮”或引用上依次调用 2 个方法

问题描述

按钮/参考应该最小化/最大化表格内的一些文本。

下面你会发现 2 个函数“blend_in”可以最大化表格中的文本,“blend_out”可以混合/最小化表格中的文本。我用 2 个按钮实现了这一点,并希望在同一个按钮/参考上使用 2 种方法。

function blend_in(id) {
  document.getElementById(id).style.display = 'block'
}

function blend_out(id) {
  document.getElementById(id).style.display = 'none'
}
<table width="100%">
  <tr>
    <td>
      //this button will open the text inside the table.
      <a href="javascript:blend_in('zeile')"> Button 1 </a>
    </td>
  </tr>
  <tr style="display:none;" id="zeile">
    <td>
      (Text of the table) //the text inside the table which will be opened by clicking "Button 1" and closes by clicking "Button 2"
      <a href="javascript:blend_out('zeile')"> Button 2 </a></td>
  </tr>
</table>

标签: htmlbuttonhtml-tablejscript

解决方案


只是一个简单的切换 - 我使用数据属性来获取目标 - 它可以用于多行:

window.onload=function() {
  var buts = document.querySelectorAll(".toggleBut");
  for (var i=0;i<buts.length;i++) {
    buts[i].onclick=function(e) {
      e.preventDefault(); // cancel the click
      var target = document.getElementById(this.getAttribute("data-blend"));
      target.style.display=target.style.display=="none"?"":"none";
    }
  }
}
a.toggleBut { text-decoration:none }
<table width="100%">
  <tr>
    <td>
      <a href="#" class="toggleBut" data-blend="zeile1"> Toggle 1 </a>
    </td>
  </tr>
  <tr style="display:none;" id="zeile1">
    <td>Text of the table 1</td>
  </tr>
  <tr>
    <td>
      <a href="#" class="toggleBut" data-blend="zeile2"> Toggle 2 </a>
    </td>
  </tr>
  <tr style="display:none;" id="zeile2">
    <td>Text of the table 2</td>
  </tr>
</table>


推荐阅读