问题
This was asked many times, I know but this is different! I made this:

When you click on the minus icon, the column should disappear, this worked with php, but the code is a mess and I would like to get this working with jQuery, i found some other threads that showed me this:
$("#minus").click(function() {
$("#table td:nth-child(2),th:nth-child(2)").hide();
});
After a while I came up with this:
var num = $("#columnid").index();
$("#table td:nth-child("+ num +"),th:nth-child("+ num +")").hide();
That kinda worked, but i need to call it with a onclick="jquery_function();"
function and let php insert the id of every header, but is this possible? Or what is the other way of doing this? i'm stuck!
This did it:
$(".minus").click(function() {
var num = $(this).parent().index() + 1;
$("#table td:nth-child("+ num +"),th:nth-child("+ num +")").fadeOut(250);
});
Seems simple after figuring out, Jeroen had it right. :) The only thing i dont get is why you need the ("th"), works with and without. Thanks!
回答1:
It seems you've almost got it complete. What you could do, is wrap it in a function and attach the event handler to the button in the table header cell:
$("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;
}
回答2:
How about this?
// 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();
});
Untested, and feel free to omit code as you see fit.
来源:https://stackoverflow.com/questions/8702641/hide-table-column-with-jquery