获取单击列中第一个单元格的内容以及HTML表格中单击行的第一个单元格

时间:2013-11-28 18:38:09

标签: javascript html

我正在使用以下javascript来获取单击的表格单元格中的数据:

var table = document.getElementById('ThisWeek'),
    cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i<len; i++)
{
    cells[i].onclick = function()
    {
        document.getElementById("txtVal").value = this.innerText;
    }
}

如何修改此项,以便我还可以获取所单击列中第一个单元格的内容以及所单击行中的第一个单元格?例如。如果我点击下表中的“s”,我得到结果“2”和“B”作为两个变量返回:

0 1 2 3
A q w e
B a s d
C z x c

请注意,我需要一个javascript解决方案,而不是jQuery。理想情况下,我还想点击第一行和第一列来返回空字符串。

3 个答案:

答案 0 :(得分:1)

此代码段使用我在评论中提到的属性:

window.onload = function () {
    var table = document.getElementById('table');
    table.addEventListener('click', function (e) {
        var target = e.target,
            col = target.cellIndex,
            row;
        while (target = target.parentElement) {
            if (!col && col !== 0) {
                col = target.cellIndex;
            }
            if (target.tagName.toLowerCase() === 'tr') {
                row = target.rowIndex;
                break;
            }               
        }
        console.log(table.rows[row].cells[0].innerHTML + ', ' + table.rows[0].cells[col].innerHTML);
    });
}

A live demo at jsFiddle

答案 1 :(得分:1)

我建议:

function index(c){
    var i = 0;
    while (c.previousSibling){
        /* if the previousSibling has a nodeType and that nodeType === 1 
           (indicating the previousSibling is an element) increment the i variable */
        if (c.previousSibling.nodeType && c.previousSibling.nodeType === 1){
            i++;
        }
        // reset c to the previousSibling
        c = c.previousSibling;
    }
    /* i is the count of previous-siblings, and therefore the index
       amongst those siblings: */
    return i;
}

function getHeaders(e){
    /* this is the table element,
       e.target is the clicked element */
    var el = e.target,
        text = 'textContent' in document ? 'textContent' : 'innerText',
        headers = [el.parentNode.getElementsByTagName('td')[0][text],this.getElementsByTagName('tr')[0].getElementsByTagName('td')[index(el)][text]];
    // set the text of the nextElementSibling of the table:
    this.nextElementSibling[text] =  headers.join(', ');
}

document.getElementById('table').addEventListener('click', getHeaders);

JS Fiddle demo

答案 2 :(得分:1)

您可以将其添加到您的单元格[i] .onclick function:

var row = this.parentElement; // TR
var table = row.parentElement.parentElement; // TBODY > TABLE
document.getElementById("columnVal").value = row.rowIndex && this.cellIndex ? table.rows[0].cells[this.cellIndex].innerText : "";
document.getElementById("rowVal").value = row.rowIndex && this.cellIndex ? row.cells[0].innerText : "";