简体   繁体   中英

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. In some of the cells there is a catalog string, catalogIndex , that is truncated via CSS. I want to be able to add a title attribute to those specific cells so that users can see the entire string.

I've tried using the .attr method in jQuery like this:

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

queueRow is a variable that holds the actual row for an HTML table. 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. 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:

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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