【问题标题】:Hide table column with jQuery使用 jQuery 隐藏表格列
【发布时间】:2012-01-31 22:11:17
【问题描述】:

这个问题被问过很多次了,我知道,但这次不一样!我做了这个:

当您单击减号图标时,该列应该消失,这适用于 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”),不管有没有。谢谢!

【问题讨论】:

  • Datatables.net 可以通过两种方式显示/隐藏列,datatables.net/examples/api/show_hide.htmldatatables.net/extras/colvis 具有状态保存功能
  • 您的意思是在<td> 标签内回显ID?如果这就是你所需要的,那几乎就是<td id="<?= $id; ?>">……但我不认为就是这样。你能解释一下你还需要什么吗?
  • 这个想法是像 javascript 一样使用 jQuery.. 像这样:onclick="someFunction();"但是其他人建议的方式更像是jQuery'ish。 :)
  • @Gideon 我添加了th,因为我不知道th 是否是您按钮的直接父级;表格单元格中可能存在 div 或 span,因此我使用 .parents("th") 寻找最近的 th 元素。

标签: jquery hide selector


【解决方案1】:

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

$("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;
}

【讨论】:

  • 啊,所以我只需要让 var num 更具动态性,感谢您的想法,稍后会尝试!
  • @Gideon 没错,你不需要ID,你只需要找出在哪个th被点击的按钮。
【解决方案2】:

这个怎么样?

// 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();
});

未经测试,您可以随意省略您认为合适的代码。

【讨论】:

  • 看到我现在拥有的工作代码,这应该可以工作。只是看起来很乱,但也许就是我。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多