簡體   English   中英

jQuery:如何將表格屬性動態添加到一行中的特定單元格?

[英]jQuery: How can I dynamically add a table attribute to a specific cell in a row?

我有一個通過JavaScript和jQuery生成的表。 在某些單元格中,有一個目錄字符串catalogIndex ,可通過CSS截斷。 我希望能夠為這些特定的單元格添加一個title屬性,以便用戶可以看到整個字符串。

我試過像這樣在jQuery中使用.attr方法:

$(queueRow[5]).attr('title', catalogIndex);

queueRow是一個變量,用於保存HTML表的實際行。 在代碼的前面,我使用以下代碼創建了它:

var queueRow = document.getElementById("copyQueue").insertRow();

我可以這樣插入單個單元格:

    //variable that uses queueRow and creates a new cell.
    var catCell = queueRow.insertCell();

    //add text to the cell using the content of catalogIndex
    catCell.innerHTML = catalogIndex;

我試圖定位適當的單元格(在我的情況下,為queueRow的第6個位置)並添加title屬性。 我沒有收到任何錯誤,但似乎未向該單元中添加任何內容。 獲取我想要的單元格位置的正確語法是什么?

您可以使用cells屬性:

var queueRow = document.getElementById("copyQueue").insertRow();
// ...
var catCell = queueRow.insertCell();
catCell.textContent = catalogIndex; // don't use innerHTML for pure text.
// ...
$(queueRow.cells[5]).attr('title', catalogIndex);

但是您應該嘗試使用更多的jQuery。 例如:

var $queueRow = $("<tr>").appendTo("#copyQueue");
// ...
var $catCell = $("<td>").appendTo($queueRow).text(catalogIndex);
// ...
$("td", $queueRow).eq(5).attr('title', catalogIndex);

但是,如果您已經有了$catCell ,則可能無需再次查找該單元格,並且可以一次完成最后兩個操作:

$("<td>").appendTo($queueRow).text(catalogIndex).attr("title", catalogIndex);

暫無
暫無

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

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