簡體   English   中英

獲取單擊列中第一個單元格的內容以及HTML表格中單擊行的第一個單元格

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

我正在使用以下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。 理想情況下,我還想點擊第一行和第一列返回空字符串。

此代碼段使用我在評論中提到的屬性:

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小提琴演示

你可以將它添加到你的單元格[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 : "";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM