0

我在表格单元格中列出了一系列输入,例如电子表格。我只是想让 jquery 在我开始输入时找出它们在哪一列。我想这样做而不将标识符放在列本身中。

http://jsfiddle.net/jx3FP/

我已经使用 jquery 的索引进行了几次尝试,但我显然遗漏了一些东西。当我尝试获取表数据(td)的索引时,我为文档获取它,而不是为它的父级获取它。当我尝试指定父母和孩子时,它似乎不是索引所做的事情。提前感谢您的帮助。

$('tr td input').live('keyup',function(e){
    /* attempt 1, returns nth td in document instead of the nth td in the table row
    var column = $(this).parent().index('td');
    $('#column').val(column);
    */
    /* attempt two */
    $parentRow = $(this).parents('tr');
    $parentCell = $(this).parent('td');
    var $column = $(this).parent('td').index('tr');
    // insert column number into #column
    var $column = ($parentRow).index($parentCell);
    $('#column').val($column);
});
4

2 回答 2

0

您正在寻找closest,不是parentparents

var cellThisInputIsIn = $(this).closest('td');
var theCellsIndexWithinTheRow = cellThisInputIsIn.index();
var rowThisInputIsIn = $(this).closest('td');
var theRowsIndexWithinTheTableBody = rowThisInputIsIn.index();

一旦你拥有了单元格/行和/或它们的索引,不清楚你想对它/它们做什么,但这就是你找到它/它们的方式。

于 2014-04-20T17:51:38.750 回答
0

jsfiddle:http: //jsfiddle.net/jx3FP/1/

html

<table>
    <tr>
        <td>
            <input />
        </td>
        <td>
            <input />
        </td>
        <td>
            <input />
        </td>        
    </tr>
    <tr>
        <td>
            <input />
        </td>
        <td>
            <input />
        </td>
        <td>
            <input />
        </td>        
    </tr>    
</table>
<br />
<input id="column" placeholder="column" />
<input id="row" placeholder="row" />

JS

$('tr td input').live('keyup',function(e){
        /* attempt 1, returns nth td in document instead of the nth td in the table row
        var column = $(this).parent().index('td');
        $('#column').val(column);
        */
        /* attempt two */
        var cellThisInputIsIn = $(this).closest('td');
        var rowThisInputIsIn = $(this).closest('tr');
        var $column = cellThisInputIsIn.index();
        var $row = rowThisInputIsIn.index();
        $('#column').val($column);
        $('#row').val($row);
    });
于 2014-04-20T17:58:46.227 回答