2017-10-20 144 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; 
} 
相关问题