2016-04-19 22 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

関連する問題