jquery - 尝试使用 jQuery 隐藏 html 表的列

标签 jquery html

function func(id) 
    {

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

            });
        });
        return false;
        }

我正试图隐藏与单击的按钮对应的列。但是这段代码会得到一些意想不到的输出,比如单击一个按钮时两列都隐藏了。我哪里错了?

<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>

最佳答案

一个更简单的方法是在您的列 td 中添加一个类。我将 col1col2 类添加到您的每个 td。

fiddle :http://jsfiddle.net/tbpMX/

代码:

$(".toggle").click(function() {
    $(this).parent().hide();
    $(".col" + $(this).attr("id")).hide();
});

关于jquery - 尝试使用 jQuery 隐藏 html 表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16442332/

相关文章:

css - 即使通过添加 css 文件并与 html 文件链接,Bootstrap 按钮颜色也不会改变?

javascript - jQuery 和自动调整文本区域大小的问题

JavaScript/JQuery 在加载了 load() 的 html 中不起作用

jquery - fullcalendar2 每个工作日的 minTime 和 maxTime

javascript - Jquery Accordion 在单击时滑回?

html - 切换服务器时失去响应

html - 将 2 列布局环绕图像

jquery Ajax 没有响应?

jquery - 触摸事件在触摸屏笔记本电脑上不起作用

javascript - 具有最大缓冲区的 <Textarea>