簡體   English   中英

如何在 jquery 中按索引查找 td

[英]how to find a td by index in jquery

我如何通過按索引獲取元素來更改內部 html
我想根據它們的索引值更改單元格的內容

<table>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
function LFLS() {
    // LFLS => load from local Storage
    for (i = 0; i < localStorage.length; i++) {
        key = localStorage.key(i);//it return values like ("1,2","2,5", etc.)
        console.log(key)
        row = key.split(",")[0];
        col = key.split(",")[1];
//how to get the cell by row and col
}
}

正如 Sakil 所說,您可以使用 eq()。 嘗試這個:

function LFLS() {
    // load from local Storage
    for (i = 0; i < localStorage.length; i++) {
        key = localStorage.key(i);
        row = key.split(",")[0];
        col = key.split(",")[1];
        // how to get the cell by row and col
        $("table tr").eq(row).children().eq(col).html('NEW VALUE')
    }
}

我相信你需要以下片段。

在你的 for 循環之前

const rows = $("table tr");

獲得 row & col 變量后

const cellToUpdate = rows[row].children[col];

或者,如果您希望以編程方式循環遍歷表格,您可以使用以下代碼段。

<script type="text/javascript">

    const rows = $("table tr");
    for( i = 0; i < rows.length; i++ ) {
        const currRow = rows[i];
        const rowChildren = currRow.children;
        for( n = 0; n < rowChildren.length; n++ ) {
            const cell = rowChildren[n];
            cell.innerHTML = "My new data for row: " + i + " in cell " + n;
        }
    }
</script>

出於某種原因,以下內容是否對您不起作用?

$("table tr:nth-of-type([your-row])).eq([your-col]).html([your_content]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM