我有这个表http://codepen.io/MetCastle/pen/lxceL,我希望使用jQuery隐藏/显示列,具体取决于input type="number"
。意思是整个列:
Proveedor 1
Proveedor 2
Proveedor 3
Proveedor 4
Proveedor 5
Proveedor 6
我不知道该怎么做。我尝试了:nth-child()
选择器,但我不明白它是如何工作的。
我做了这个功能,但显然它不完整:
$(document).ready(function() {
if ($( ".size").val() == 1)
// hide Proveedor 1
else if ($( ".size").val() == 2)
// hide Proveedor 2
});
答案 0 :(得分:0)
使用:nth-child()
选择器隐藏" nth"每行tr
元素后面的元素。例如,
if ($( ".size").val() == 1){
$('tr td:nth-child(1)').hide();
//include this line only if you also have a thead element with headings
$('tr th:nth-child(1)').hide();
}
else if ($( ".size").val() == 2){
$('tr td:nth-child(2)').hide();
//include this line only if you also have a thead element with headings
$('tr th:nth-child(2)').hide();
}
答案 1 :(得分:0)
在这里非常灵活地考虑colspans ...我认为这对你有用:
JSFiddle :(我在.size
值中添加了2,因此您会看到它删除了" Proveedor 2"以及其下的列,您可以在HTML中更改此值用不同数字测试小提琴的部分)
$(document).ready(function () {
var column = 0;
var colspan;
$("tr").eq(0).find("th").each(function () {
$this = $(this);
if ($.trim($this.text()) === "Proveedor "+$(".size").val()) {
$this.hide();
colspan = +$this.attr("colspan") || 1;
return false;
}
column += +$this.attr("colspan") || 1;
});
$("tr:gt(0)").each(function () {
var currCol = 0;
$(this).find("td, th").each(function () {
$this = $(this);
if (column === currCol) {
$this.hide();
for(i = +$this.attr("colspan") || 1; i < colspan;) {
$this = $this.next();
$this.hide();
i += +$this.attr("colspan") || 1;
}
return false;
}
currCol += +$this.attr("colspan") || 1;
});
});
});
注意:
+$this.attr("colspan") || 1
前面的+
是将其转换为数字(来自字符串)。如果未定义colspan,它将等同于假值(NaN
),然后该值将移至1
(如果colspan
未定义,则为默认值)。所以如果定义了colspan,它将是定义的任何内容,否则它将是1。
在澄清一些要求之后,这里有一个修改。处理colspans和rowpans的代码变得相当复杂......
$(":input").on('change', function () {
$("td, th").show();
var column = 0;
var colspan = 0;
var rowspanning = [];
$("tr").eq(0).find("th").each(function () {
$this = $(this);
if ($.trim($this.text()) === "Proveedor " + $(".size").val()) {
$this.nextAll().hide();
colspan = +$this.attr("colspan") || 1;
rowspanning[column] = $this.attr("rowspan")-1 || 0;
return false;
}
column += +$this.attr("colspan") || 1;
});
if (column) {
$("tr:gt(0)").each(function () {
var currCol = 0;
$(this).find("td, th").each(function () {
$this = $(this);
if(rowspanning[currCol] > 0) {
--rowspanning[currCol];
++currCol;
}
rowspanning[currCol] = $this.attr("rowspan")-1 || 0;
if (column === currCol) {
for (i = +$this.attr("colspan") || 1; i < colspan;) {
$this = $this.next();
i += +$this.attr("colspan") || 1;
}
$this.nextAll().hide();
return false;
}
currCol += +$this.attr("colspan") || 1;
});
});
}
});