我正在尝试使用 td 属性循环遍历当前显示的所有表格。
var name = "";
var theCell = "";
var width1 = "";
var width2 = "";
var intX = 0;
$("td").each(function (inx) {
name = $(this).data("colname");
theCell = $('[data-colname="' + name + '"]')[0];
console.log(theCell);
if (typeof theCell != 'undefined') {
width1 = theCell.scrollWidth;
width2 = theCell.clientWidth;
//console.log(width1);
if (width1 > width2) {
//console.log(theCell);
$(theCell).ellipsis({ lines: 1 });
$(theCell).css({ 'background-color': '#000' });
}
}
});
console.log(theCell)的输出:
<td data-colname="number_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">1</td>
<td data-colname="line_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">1</td>
<td data-colname="network_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">Welcome 1</td>
...more here...
<td data-colname="number_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">45</td>
<td data-colname="line_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">2</td>
<td data-colname="network_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">Welcome 2</td>
...more here...
<td data-colname="number_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">23</td>
<td data-colname="line_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">775</td>
<td data-colname="network_0" class="jsgrid-cell jsgrid-align-left" style="width: 80px;">Welcome 3</td>
...more here...etc etc...
在页面上它看起来像这样:
但是,它似乎只是循环第一个td,仅此而已。我认为这是由于 [0] 造成的,但我不确定需要做什么才能让它循环每个 td ?
它循环遍历每个 TD,因为我将其全部包装在 jquery every 函数中,但它只是在第一个 td 行处继续循环。每行都被命名为相同的东西(又名 data-colname="number_0"、data-colname="line_0" 等...),所以我无法寻找它区分一行与另一行..
最佳答案
我的猜测是你想这样做:
$('td').each(function (index, elem) {
if (elem.scrollWidth > elem.clientWidth) {
// console.log(elem);
$(elem).ellipsis({ lines: 1 }).css({ 'background-color': '#000' });
}
});
在 .each
中包含第二个参数处理程序使您可以直接访问正在循环的元素。
代码中的这一行:
theCell = $('[data-colname="' + name + '"]')[0];
由于 [data-colname="' + name + '"]
选择器,只会拉回第一个 td
,因为表格中的每一行似乎共享相同的 data-colname
属性。
关于javascript - jQuery 循环遍历 TD 并检查具有相同属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46920083/