2017-10-20 36 views
-2

我有一個包含多行和多列的HTML表格。我也有一個名爲userRowIndex的變量,它具有保存在其中的特定行的索引。我希望能夠使用JavaScript和我的userRowIndex變量來使整行內容可編輯。我怎樣才能做到這一點?我可以使用Javascript通過rowIndex查找表格行嗎?

+0

您使用的是JavaScript庫? –

+0

不,我沒有使用JS庫,我也不太喜歡使用其中一個。 –

+0

你可以在'nnth-CSS'選擇器中使用'document.querySelector'來實現這個功能。 – Amy

回答

1

var rows = document.getElementById("myTable").getElementsByTagName('tr'); 
 
// whatever your userRowIndex is : 
 
var userRowIndex = 1; 
 

 
rows[userRowIndex].className = 'red';
<html> 
 
<head> 
 
    <style type='text/css'> .red{color:red;}</style> 
 
</head> 
 
<body> 
 
<table id="myTable"> 
 
\t <tr> 
 
\t \t <td>1</td> 
 
\t \t <td>One</td> 
 
\t </tr> 
 
\t <tr> 
 
\t \t <td>2</td> 
 
\t \t <td>Two</td> 
 
\t </tr> 
 
\t <tr> 
 
\t \t <td>3</td> 
 
\t \t <td>Three</td> 
 
\t </tr> 
 
</table> 
 
</body> 
 
</html>

+0

這種方法很好,但是在很長的桌子上它可能會造成滯後 –

0

這是一個基本的例子,如何在特定td可以使用rowIndex

// get the table 
 
var getTable = document.querySelector("#demotable"); 
 
// adding event listener 
 
getTable.addEventListener('click', function(event) { 
 
    // current cell index 
 
    var col = event.target.cellIndex, 
 
    // get index of row from td 
 
    row = event.target.parentNode.rowIndex; 
 
    // set the contenteditable property to it 
 
    this.rows[row].cells[col].setAttribute('contenteditable', 'true') 
 
})
<table border id="demotable"> 
 

 

 
    <tr> 
 
    <td>1</td> 
 
    <td>2</td> 
 
    <td>3</td> 
 
    </tr> 
 
    <tr> 
 
    <td>4</td> 
 
    <td>5</td> 
 
    <td>6</td> 
 
    </tr> 
 

 
</table>

還要注意一個td可以在編輯來爲可編輯即使t他整個行可以做編輯,但只有一個單元可以同時

0

這可能是改變更快:

function getRowByIndex(userRowIndex) 
{ 
    var rows = null; 
    var row = null; 

    try 
    { 
     rows = document.getElementById("myTable").getElementsByTagName('tr'); 

     if(rows!=null) 
     { 
      // This uses 0 based indexing, so assume that the passed value is in that range 
      row = rows[userRowIndex]; 
     } 

    } 
    catch(e) 
    { 
     alert("getRowByIndex Error: " + e.Message); 
    } 
    finally 
    { 

    } 

    return row; 
} 
相關問題