【问题标题】:How to toggle table in column on button click using jQuery's toggleClass如何使用jQuery的toggleClass在按钮单击时切换列中的表格
【发布时间】:2017-05-08 01:46:33
【问题描述】:

所以,我希望能够在单击按钮时切换表格中的列。

我查看了 jQuery 的切换类函数,并认为我可以给 th(表头)和 td(HTML 表中的单元格)相同的类,然后在单击按钮时执行一个 toggleClass。

这是我的 Dashboard.tsx 文件中的表格:

  <table>
  <thead>
  <tr>
  <th class="lastname">LastName</th>
  <tr>
  </thead>
  <tbody>
  {
   this.1stUserInfo.map((value, index, array) => {
     return(
       <tr>
          <td class="lastname">{value.LastName}</td>
       </tr>);
       }, this)
       }
       </tbody>
       </table>

这是我的按钮:

       <Button id="lastnamebutton" onClick={(e) => this.ShowLastName(e,this)}>Toggle Last Name</Button>  

这是我在 JavaScript 中实现 toggleClass 的函数

       public ShowLastName(event, caller) {
          $("#lastnamebutton").toggleClass(".lastname");
       }

我做错了什么和/或您能想出另一种方法来切换表格中的列吗?

【问题讨论】:

  • 抱歉,不清楚您想要达到的目标。您想要切换您的列(意味着隐藏和显示您的列)或 toggleClass 您的列(意味着从您的列中添加和删除类)?
  • 这是 React 吗?如果是这样,你不应该需要 jquery
  • 我想隐藏和显示我的专栏...是的,这就是 React

标签: javascript jquery html html-table


【解决方案1】:

toggleClass() 在不正确的元素上被调用。应该在.lastname 上调用它而不是#lastnamebutton

这是一个例子(顺便说一句,这种情况与 React 无关):

window.toggleColumn = function() {
  $('.yclass').toggleClass('hide');
};
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <th>X</th>
    <th class="yclass">Y</th>
    <th>Z</th>
  </thead>
  <tbody>
    <tr>
      <td>42</td>
      <td class="yclass">45</td>
      <td>46</td>
    </tr>
    <tr>
      <td>72</td>
      <td class="yclass">62</td>
      <td>22</td>
    </tr>
  </tbody>
</table>
<button onclick="window.toggleColumn()">
Click
</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多