简体   繁体   English

jQuery:如何将表格属性动态添加到一行中的特定单元格?

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

I have a table that is generated via JavaScript and jQuery. 我有一个通过JavaScript和jQuery生成的表。 In some of the cells there is a catalog string, catalogIndex , that is truncated via CSS. 在某些单元格中,有一个目录字符串catalogIndex ,可通过CSS截断。 I want to be able to add a title attribute to those specific cells so that users can see the entire string. 我希望能够为这些特定的单元格添加一个title属性,以便用户可以看到整个字符串。

I've tried using the .attr method in jQuery like this: 我试过像这样在jQuery中使用.attr方法:

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

queueRow is a variable that holds the actual row for an HTML table. queueRow是一个变量,用于保存HTML表的实际行。 Earlier in the code, I've created it using: 在代码的前面,我使用以下代码创建了它:

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

I can insert individual cells like this: 我可以这样插入单个单元格:

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

I attempted to target the appropriate cell (in my case, the 6th position of queueRow ) and add the title attribute. 我试图定位适当的单元格(在我的情况下,为queueRow的第6个位置)并添加title属性。 I don't get any errors, but nothing appears to have been added to that cell. 我没有收到任何错误,但似乎未向该单元中添加任何内容。 What's the correct syntax to get the position of the cell I want? 获取我想要的单元格位置的正确语法是什么?

You can use the cells property: 您可以使用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);

But you should try to use more of jQuery. 但是您应该尝试使用更多的jQuery。 For instance: 例如:

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

But if you already have $catCell , you maybe don't need to find that cell again, and can just do the last two actions in one: 但是,如果您已经有了$catCell ,则可能无需再次查找该单元格,并且可以一次完成最后两个操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM