将唯一的工具提示追加到 JQuery foreach 循环内表行中的最后一项



我正在尝试将工具提示附加到每行唯一的数据行中的最后一项,但是当我附加最新的项目工具提示时,它会覆盖前几行的工具提示。

这就是我想要的是:

  • 身份证 |名字
  • 933435 | 项目 1 - 将鼠标悬停在其上时,应显示"项目名称为:项目 1"。
  • 877988 | 项目 2 - 将鼠标悬停在其上时,应显示"项目名称为:项目 2"。
  • 746468 | 项目 3 - 将鼠标悬停在其上时,应显示"项目名称为:项目 3"。

但这就是我得到的:

  • 身份证 |名字
  • 933435 | 项目 1 - 将鼠标悬停在其上时显示"项目名称为:项目 3"。
  • 877988 | 项目 2 - 将鼠标悬停在其上时显示"项目名称为:项目 3"。
  • 746468 | 第 3 项
  • - 将鼠标悬停在其上时显示"项目名称为:第 3 项"。

它将工具提示追加到每行中的每个最后一个表项,而不是追加到最后添加的行的最后一项。

这是我正在使用的代码:

$.each(data, function (i, val) {
// create row of data
items = '<tr>' +
'<td>' + val.itemID + '</td>' +
'<td>' + val.itemName + '</td>'
'</tr>';
// appends the created row to the body of the table
$('tbody').append(items);
// appends a unique tooltip to the end of the added row
$('td:last-child').attr('title', 'The items name is: ' + val.itemName);
});

有没有办法解决这个问题,而无需像'<td title="">'那样将工具提示放在表项中?我尽量不那样做。任何帮助,不胜感激。

您可以附加一个 jQuery 对象并修改该对象中的td,而不是附加字符串

当您将有效的 html 片段包装在$()中时,您可以在结果对象上使用 jQuery 方法,就像它们已经在页面中

一样
$.each(data, function(i, val) {
// create row of data
var $items = $('<tr>' +
'<td>' + val.itemID + '</td>' +
'<td>' + val.itemName + '</td>'
'</tr>');
// only apply tooltip to the current row
$items.find('td:last').attr('title', 'The items name is: ' + val.itemName);
// appends the created row to the body of the table
$('tbody').append($items);

});

或者更改您的选择器,使其仅在最后一行中显示

$('tbody tr:last td:last').attr('title....

当前发生的事情是,您在循环的每次迭代中

循环遍历所有现有的最后一个子项,覆盖所有现有的子项,而不仅仅是新的子项

最新更新