【问题标题】:How to get the location(col,row) of an element, which is inside a table?如何获取表格内元素的位置(列,行)?
【发布时间】:2014-07-11 12:30:42
【问题描述】:

我正在研究 jquery 来发布输入表。所有输入都需要与其索引一起发布。我猜我不能使用输入元素的 id 或类来发布带有单元格位置信息的值。 .因为输入表是根据用户回答动态生成的。

例如;

用户在问题中输入“4”值并生成一个 3col 4row 输入表。

<table>
  <tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> 
  </tr>
  <tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> 
  </tr>
  <tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> 
  </tr>
  <tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> 
  </tr>
</table>

通过使用 jquery 处理程序,我可以存储值...

$(function () {
  $("input").change(function() {
    // save this.value() in an array.
    array.push(this.value());
  });
});

我停留在这一刻,因为我必须在表中存储带有 (x,y) 索引的值。不久;此二维表的值必须转换为 2dim。服务器端的数据数组。

类似...

$(function () {
  $("input").change(function() {
    array[this.col][this.row] = this.value();
  });
});

总结一下;

是否可以获取表格内元素的位置(列,行)?

【问题讨论】:

    标签: php jquery html arrays post


    【解决方案1】:

    你可以使用index()方法如下

    $(function () {
      $("input").change(function () {
        var row = $(this).closest('tr').index(); //index of row
        var col= $(this).closest('td').index(); //index of column
        // your code
      });
    });
    

    JSFiddle Demo

    【讨论】:

    • 如果我没记错的话,您还可以确保使用$(this).closest('tr').index('tr') 获取 tr 和 td 之间的索引,但可以肯定。里面有一些`
    【解决方案2】:

    试试这样的:

    $(function () {
        var $rows=$('tr');/* refine if using column heading row to something like $('tr:gt(0)')*/
      $("input").change(function() {
        var $row=$(this).closest('tr');
        var rowIndex=$rows.index($row);
        var colIndex=$(this).parent().index();
    
          /* do something with indexes*/
      });
    });
    

    【讨论】:

      【解决方案3】:

      如果您想在数组中存储列和行的值,您可以使用多维数组(数组数组)。
      首先,您在默认数组中插入代表您的行的其他数组,然后当字段更改时,您会将数据存储在数组第一个数据:行第二个数据列中。

      <script type="text/javascript">
      $(document).ready(function(){
        var array=[]
        for(a=0;a<$('table tr').length;a++){
           array[a]=[] 
        } 
       $("input").change(function() {
          var val=$(this).val()
          var row=$(this).parents('tr').index()
          var column =$(this).parent('td').index()
          array[row][column] = val
          console.log(array)
        });   
      })
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-05
        • 2011-08-09
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        相关资源
        最近更新 更多