获取表行列和标头JQuery

时间:2013-08-17 05:51:06

标签: javascript jquery contenteditable

我有一个令人满意的表,我想要检索已编辑单元格的行,列和标题。我已经成功获得了这一行,但我无法弄清楚如何获得标题和列...

到目前为止

代码:

document.addEventListener('keydown', function (event) {
var esc = el = event.target;
    var row = $(el).rowIndex();
}

3 个答案:

答案 0 :(得分:1)

完整解决方案:http://jsfiddle.net/pLpKm/

HTML:

<div class"info">
    <strong>Column number: </strong><span class="column"></span>
    <br/>
    <strong>Row number: </strong><span class="row"></span>
    <br/>
    <strong>Header text: </strong><span class="header"></span>
    <br/>
</div>
<table cellpadding="0" cellspacing="0" border="1" style="width:200px; height:400px;">
    <tr>
        <th>
            Heading 1
        </th>
        <th>
            Heading 2
        </th>
        <th>
            Heading 3
        </th>
    </tr>
    <tr>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
    </tr>
    <tr>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
    </tr>
    <tr>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
    </tr>
    <tr>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
        <td contentEditable>
        </td>
    </tr>
</table>

JS:

$('table').on('keydown', function(e){
    var columnNumber, rowNumber, headerText;
    columnNumber = $(e.target).index() + 1;
    rowNumber = $(e.target).parent().index() + 1;
    headerText = $('th:nth-child(' + columnNumber + ')').text();
    $('.column').html(columnNumber);
    $('.row').html(rowNumber);
    $('.header').html(headerText);
});

答案 1 :(得分:0)

<table>
<tr>
 <td>name1</td><td>name2</td><td>name3</td>
</tr>
<tr>
 <td>name2.1</td><td>name2.2</td><td>name2.3</td>
</tr>
<script>


var tds=document.getElementsByTagName('table')[0].getElementsByTagName('td');

for(var i=0;i<tds.length;i++){
tds[i].onclick=function(){
//console.log(this.parentNode.tagName)//TR
//console.log(this.parentNode);

var tr=document.getElementsByTagName('table')[0].getElementsByTagName('tr');
for(var j=0;j<tr.length;j++){
    if(tr[j]==this.parentNode){
        console.log('row:'+j);//index row
    var arrtd=tr[j].getElementsByTagName('td')
    for(var m=0;m<arrtd.length;m++){
        if(this==arrtd[m])
        console.log('col:'+m);//index col
        //break;
    }
}
}
}
}

答案 2 :(得分:0)

document.addEventListener('keydown', function (event) {
var esc = el = event.target;

esc.closest("tr");//get tr
esc.closest("td"); //get td
esc.closest("table").find("thead");//for thead header
}

参考

jquery find

jquery closest