2016-04-19 61 views
0

你好,我用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); 

} 

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

+0

你可以设置数据属性例如'data-row =“1”data-column =“4”'在你的循环中为元素。点击后,您可以简单地获取该值并使用。 –

回答

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 
} 
0

您可以使用parentNode.rowIndex & cellIndex获得细胞&的rowIndex

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

检查这jsFiddle

相关问题