【问题标题】:How to get a <td> 's position in a table using JQuery?如何使用 JQuery 在表中获取 <td> 的位置?
【发布时间】:2017-11-03 00:10:50
【问题描述】:

例如:

<table>
<tr><td>1,1</td><td>2,1</td></tr>
<tr><td>2,1</td><td>2,2</td></tr>
</table>

我想使用以下功能:

$("td").click(function(){
alert(xxxx)
})

点击时获取&lt;td&gt; 的位置,但是如何?

【问题讨论】:

    标签: jquery html-table


    【解决方案1】:

    不带参数调用的index 函数将获得相对于其兄弟的位置(无需遍历层次结构)。

    $('td').click(function(){   
       var $this = $(this);
       var col   = $this.index();
       var row   = $this.closest('tr').index();
    
       alert( [col,row].join(',') );
    });
    

    【讨论】:

      【解决方案2】:

      Core / index

      $("td").click(function(){
      
          var column = $(this).parent().children().index(this);
          var row = $(this).parent().parent().children().index(this.parentNode);
      
          alert([column, ',', row].join(''));
      })
      

      【讨论】:

        【解决方案3】:

        根据this answer,DOM Level 2 分别公开了tdtr 元素的cellIndexrowIndex 属性。

        让你这样做,可读性很好:

        $("td").click(function(){
        
            var column = this.cellIndex;
            var row = $(this).parentNode.rowIndex;
        
            alert("[" + column + ", " + row + "]");
        });
        

        【讨论】:

        【解决方案4】:

        在 jQuery 1.6 中:

        $(this).prop('cellIndex')
        

        【讨论】:

          【解决方案5】:

          $("td").click(function(e){
            alert(e.target.parentElement.rowIndex + " " + e.target.cellIndex)
          });
          tr, td {
            padding: 0.3rem;
            border: 1px solid black
          }
          
          table:hover {
            cursor: pointer;
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <table>
            <tr>
              <td>0, 0</td>
              <td>0, 1</td>
              <td>0, 2</td>
            </tr>
            <tr>
              <td>1, 0</td>
              <td>1, 1</td>
              <td>1, 2</td>
            </tr>
          </table>

          【讨论】:

            猜你喜欢
            • 2010-09-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-01
            • 2015-08-16
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多