如何找出点击了哪一行?

时间:2016-04-19 17:17:42

标签: javascript html

你好我用javascript生成一个表,现在我不知道用户点击了哪一行和哪一行?

以下是我对该表的功能:

function doNextSteps() {

    removeAustriaFromCountries();

    //insert table
    var table = document.createElement("table");
    table.setAttribute('id', 'matrixTable');
    table.setAttribute('class', 'jbiTable');

    // insert MATRIX row
    var matrixRow = table.insertRow();
    var cell = matrixRow.insertCell(); // left column for countries
    cell.setAttribute('class', 'jbiMatrixCell');
    cell.setAttribute('colSpan', departments.length + 1);
    cell.appendChild(document.createTextNode("MATRIX"));

    // insert departments row
    var departmentsRow = table.insertRow();
    var cell = departmentsRow.insertCell(); // left column for countries
    cell.setAttribute('class', 'jbiBlankCell');

    for (var i = 0; i < departments.length; i++) {
        var cell = departmentsRow.insertCell();
        cell.appendChild(document.createTextNode(departments[i].name));
        cell.setAttribute('class', 'jbiDepartmentCell');
    }

    for (var i = 0; i < countries.length; i++) {
        var countryRow = table.insertRow();
        var cell = countryRow.insertCell(); // left country column
        //cell.appendChild(document.createTextNode(countries[i].name)); 
        var img = document.createElement('img');
        img.src = "example.com + flags[i].name";
        cell.appendChild(img);
        cell.setAttribute('class', 'jbiCountryCell');
        for (var j = 0; j < departments.length; j++) {
            var cell = countryRow.insertCell();
            var img = document.createElement('img');
            img.src = "https://intranet.windkraft.at/OrganisationManual/Documents/Kreis.jpg";
            img.onclick = function () {
                window.location.href = "example.com" + pdfFiles[i].name;
            };
            cell.appendChild(img);
            cell.setAttribute('class', 'jbiCircleCell');
        }
    }


    $("#divTable").append(table);

}

生成表格,现在我想知道用户点击了哪个标题和哪一列。有了这些信息,我想创建一个新的查询来获取动态显示在表中的文件。任何帮助都会很棒。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

要获取行的索引,可以在事件侦听器函数中使用此代码:

function onClick() {
  var cell = this;
  var row = cell.parentNode;
  var cellIndex = Array.prototype.indexOf.call(row.children, cell);
  var rowIndex = Array.prototype.indexOf.call(row.parentNode.children, row);

  // do stuff with rowIndex, cellIndex
  // rowIndex is the row number starting with row 0
  // cellIndex is the column number starting with column 0
}

答案 1 :(得分:0)

您可以使用parentNode.rowIndex&amp; cellIndex获取细胞和细胞rowIndex位置

document.getElementsByTagName('table')[0].addEventListener('click', function(e) {
  console.log(e.target.parentNode.rowIndex,' ',e.target.cellIndex);
 }, false);

选中此jsFiddle