Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以使用Javascript通过表的行索引查找表行吗?_Javascript_Html - Fatal编程技术网

我可以使用Javascript通过表的行索引查找表行吗?

我可以使用Javascript通过表的行索引查找表行吗?,javascript,html,Javascript,Html,我有一个包含多行和多列的HTML表。我还有一个名为userRowIndex的变量,其中保存了某一行的索引。我希望能够使用JavaScript和我的userRowIndex变量使整行内容可编辑。我该怎么做? var rows=document.getElementById(“myTable”).getElementsByTagName(“tr”); //无论您的userRowIndex是什么: var userRowIndex=1; 行[userRowIndex]。类名='red' .red{c

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

var rows=document.getElementById(“myTable”).getElementsByTagName(“tr”);
//无论您的userRowIndex是什么:
var userRowIndex=1;
行[userRowIndex]。类名='red'

.red{color:red;}
1.
一
2.
二
3.
三

这是一个基本示例,说明如何使用
行索引使特定的
td
可编辑

//获取表
var getTable=document.querySelector(“可降级”);
//添加事件侦听器
getTable.addEventListener('click',函数(事件){
//当前单元格索引
var col=event.target.cellIndex,
//从td获取行的索引
行=event.target.parentNode.rowIndex;
//将contenteditable属性设置为它
this.rows[row].cells[col].setAttribute('contenteditable','true')
})

1.
2.
3.
4.
5.
6.
这可能更快:

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

你使用的是JavaScript库吗?不,我没有使用JS库,我也不太喜欢使用JS库。你可以使用
document.querySelector
nth-child
CSS选择器来使用vanilla JS实现这一点。所以选择所有的行,在索引处抓取一行。@Amy我喜欢你的想法。实际上,我刚刚找到了一种保存行id的方法,这样我就可以使用id选择器了,不过还是要感谢您的评论。这种方法很好,但是在很长的表上,它可能会导致延迟