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

Get contents of the first cell in the clicked column and the first cell of the clicked row in a HTML table

本文关键字:第一个 单击 单元 HTML 获取 单元格      更新时间:2023-11-26

我正在使用以下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"answers"B":

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

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

这个片段使用了我在评论中提到的属性:

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);
    });
}

jsFiddle的现场演示。

我建议:

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演示。

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

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 : "";