我可以使用Javascript通过其rowIndex查找表行吗?

时间:2017-10-20 15:48:07

标签: javascript html

我有一个包含多行和多列的HTML表。我还有一个名为userRowIndex的变量,它具有保存在其中的某一行的索引。我希望能够使用JavaScript和我的userRowIndex变量使整个行内容可编辑。我怎么能这样做?

3 个答案:

答案 0 :(得分: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">
	<tr>
		<td>1</td>
		<td>One</td>
	</tr>
	<tr>
		<td>2</td>
		<td>Two</td>
	</tr>
	<tr>
		<td>3</td>
		<td>Three</td>
	</tr>
</table>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是使用td

如何使特定rowIndex可编辑的基本示例

&#13;
&#13;
// 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')
})
&#13;
<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>
&#13;
&#13;
&#13;

另请注意,一次td可以编辑。即使整个行可以编辑,但一次只能更改一个单元格

答案 2 :(得分: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;
}