尝试使用jQuery隐藏html表的列 [英] Attempting to hide a column of a html table using jQuery

查看:82
本文介绍了尝试使用jQuery隐藏html表的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数func(id)
{

$(document).ready(function()
{
$ (.toggle)。click(function()
{
$(td:nth-​​child(+ id +)> div)。toggle();

});
});
返回false;
}

我试图隐藏与点击按钮相对应的列。但是这个代码会得到一些意想不到的输出,例如当点击一个按钮时隐藏的列。

 < table border =1> 
< tr>
< th>< button class =toggleid =1onclick =return func(this.id); >隐藏< /按钮>< /第>
< th>< button class =toggleid =2onclick =return func(this.id); >隐藏< /按钮>< /第>
< / tr>
< tr>
< td> < div>第1行,第1单元< / div>< / td>
< td>< div>第1行,第2单元< / div>< / td>
< / tr>
< tr>
< td>< div>第2行,第1单元< / div>< / td>
< td> < div>第2行,第2单元< / div>< / td>
< / tr>
< / table>


解决方案



在你的jquery中你可以有:

  $ (#1,#2)。click(function(){
$(this).find(td)。hide();
});

编辑:

给列名提供id名:

  $(document).ready(function(){
$(# 1,#2)。click(function(){
var colid = $(this).prop(id);
$(tr)。children()。each(function (){
if(colid == 1)
{
$(this).closest(td:nth-​​child(1),th:nth-​​child(1)) .hide();
}
else
{
$(this).closest(td:last-child,th:last-child)。hide();
}

});
});

});



下面是实际的小提琴

a>。


function func(id) 
    {

        $(document).ready(function () 
        {
            $(".toggle").click(function () 
            {
                $("td:nth-child(" + id + ")>div").toggle();

            });
        });
        return false;
        }

Am attempting to hide the column corresponding to the button clicked. But this code gets some unexpected output like both the columns hiding when one button is clicked. where am i going wrong?

<table border="1">
<tr>
 <th><button class="toggle" id="1" onclick="return func(this.id);" >hide</button></th>
  <th><button class="toggle" id="2" onclick="return func(this.id);" >hide</button></th>
  </tr>
  <tr>
  <td> <div>row 1, cell 1</div></td>
  <td><div>row 1, cell 2</div></td>
  </tr>
  <tr>
  <td><div>row 2, cell 1</div></td>
  <td> <div>row 2, cell 2</div></td>
  </tr>
  </table>

解决方案

You don't need onclick on your html to call the function.

In your jquery you could have:

$("#1,#2").click(function(){
$(this).find("td").hide();
});

Edit:

This one without resorting to giving id names to column:

$(document).ready(function(){
$("#1,#2").click(function(){
    var colid=$(this).prop("id");
    $("tr").children().each(function(){
        if (colid==1)
        {
           $(this).closest("td:nth-child(1),th:nth-child(1)").hide();                
        }
        else
        {
            $(this).closest("td:last-child,th:last-child").hide();
        }

    });
});

});

Here's the actual fiddle.

这篇关于尝试使用jQuery隐藏html表的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆