使用jQuery隐藏表列

时间:2012-01-02 15:40:34

标签: jquery hide selector

这被问过很多次,我知道但这是不同的!我做了这个:

enter image description here

当你点击减号图标时,列应该会消失,这可以用PHP工作,但代码很乱,我想用jQuery工作,我发现其他一些线程向我展示了这个:

$("#minus").click(function() {
    $("#table td:nth-child(2),th:nth-child(2)").hide();
});

过了一会儿我想出了这个:

var num = $("#columnid").index();    
$("#table td:nth-child("+ num +"),th:nth-child("+ num +")").hide();

有点工作,但我需要用onclick="jquery_function();"函数调用它,让php插入每个标题的id,但这可能吗?或者这样做的另一种方式是什么?我被卡住了!

这样做了:

$(".minus").click(function() {
    var num = $(this).parent().index() + 1;
    $("#table td:nth-child("+ num +"),th:nth-child("+ num +")").fadeOut(250);
});

在弄清楚之后似乎很简单,Jeroen说得对。 :)我唯一没有得到的是为什么你需要(“th”),使用和不使用。谢谢!

2 个答案:

答案 0 :(得分:2)

看来你几乎完成了它。你可以做的是将它包装在一个函数中,并将事件处理程序附加到表头单元格中的按钮:

$("th .button").click(function(){
  var num = $(this).parents("th").index();    // untested, but something like this should do it
  $("#table td:nth-child("+ num +"),th:nth-child("+ num +")").hide();
  return false;
}

答案 1 :(得分:0)

这个怎么样?

// note the class for multiple minus
$(".minus").click(function () {
  var $this = $(this);
  var index = $('.minus').index($this); // get the zero based index of this element
  index++; // adjust for zero based index
  var selector = '#table td:nth-child(' + index + '), the:nth-child(' + index + ')';
  $(selector).hide();
});

未经测试,您可以根据需要随意省略代码。