Javascript jQuery通过TD循环并检查具有相同属性的值
我正在尝试使用td属性遍历当前显示的所有表Javascript jQuery通过TD循环并检查具有相同属性的值,javascript,jquery,each,Javascript,Jquery,Each,我正在尝试使用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
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.logtheCell的输出:
在页面上看起来是这样的:
然而,它似乎只是循环通过第一个td,仅此而已。我认为这是由于[0]造成的,但我不确定需要做什么才能使它循环通过每个td
它是通过每个TD循环的,因为我将它全部包装在jquery-each函数中,但它只是在第一个TD行保持循环。每一行的名称都是相同的,即data colname=number\u 0,data colname=line\u 0,等等。。。因此,我无法用它来区分一行和另一行。我猜您想这样做:
$('td').each(function (index, elem) {
if (elem.scrollWidth > elem.clientWidth) {
// console.log(elem);
$(elem).ellipsis({ lines: 1 }).css({ 'background-color': '#000' });
}
});
在处理程序中包含第二个参数,可以直接访问正在循环的元素
代码中的这一行:
theCell = $('[data-colname="' + name + '"]')[0];
由于[data colname='+name+']选择器,表中的每一行似乎共享相同的data colname属性,因此将只回拉第一个td。每个循环都获得相同的$'[data colname='+name+']'。创建选择器以查找与前一行相同的元素没有意义。另外,选择器总是返回页面中第一个带有该属性的td。代码有很多问题,但您到底想实现什么呢?是否要修改正在循环的每个单元格的显示?看起来您正在尝试重新选择与该数据属性匹配的任何单元格,但只选择作为DOM节点返回的第一个元素,而不是jQuery对象。。。这就是你想要的吗?如果你试图修改你所在的单元格,那么你可以使用$this。。。你们可能也不希望所有这些变量都在每个变量的范围之外。这就是皮特!谢谢
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' });
}
}
});