【问题标题】:Using jQuery, how can I reference a html table cell td from a checkbox inside the cell?使用 jQuery,如何从单元格内的复选框中引用 html 表格单元格 td?
【发布时间】:2017-07-25 05:43:54
【问题描述】:

我有一个 html 表格:

  <table>
         <tr>
              <td>
                  <input type="checkbox" name="myCheck">
              </td>
         </tr>
  </table>

单击复选框时,我想更改表格单元格的背景颜色。表格单元格似乎不是复选框的父级。

在单击复选框时获取对表格单元格的引用的正确方法是什么?

【问题讨论】:

    标签: jquery checkbox html-table


    【解决方案1】:

    当我点击复选框时,我想更改表格单元格的背景色。

    您可以在更改事件中使用当前单击的复选框上下文 this.parent() 来定位 td 元素:

    $('input[name="myCheck"]').change(function(){
      $(this).parent().css('background',this.checked?"red":"");
    });
    

    DEMO

    【讨论】:

      【解决方案2】:

      要获取父表格单元格(例如 td 元素),您可以像这样使用.closest("td")

      $("input").change(function() {
          var td = $(this).closest("td");
      });
      

      在这种特殊情况下,您也可以只使用$(this).parent(),但使用$(this).closest("td") 更简单一些,因为它会找到最近的父对象,即 td 并且如果放置了input 元素,则不会受到影响出于格式化原因,在 div 或其他一些 HTML 元素中 - 因此使用 .closest("td") 的它不那么脆弱,因此建议使用。

      【讨论】:

        【解决方案3】:

        $('input').on('change', function () {
          if(this.checked){
             $(this).parent().css("background","blue"); 
          }
          else{
             $(this).parent().css("background","");
          }
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <table>
                 <tr>
                      <td>
                          <input type="checkbox" name="myCheck">
                      </td>
                 </tr>
          </table>

        【讨论】:

          【解决方案4】:

          使用.closest('td')方法获取最近的td父元素。

          $('input[name="myCheck"]').on('change', function () {
              $(this).closest('td');
          });
          

          Example Here

          只需监听所需元素的change 事件并从那里调用.closest() 方法。

          $('input[name="myCheck"]').on('change', function () {
              $(this).closest('td').toggleClass('active');
          });
          .active {
              background: red;
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <table>
              <tr>
                  <td>
                      <input type="checkbox" name="myCheck"/>
                  </td>
              </tr>
          </table>

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-07-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-10-19
            • 2011-03-19
            • 2011-06-30
            相关资源
            最近更新 更多