javascript - jQuery - 切换按钮显示/隐藏表数据

标签 javascript jquery html

我需要一些帮助。

<h2>Operating systems <span class="button small toggle-btn">Toggle</span></h2>
<table class="data" cellpadding="8" border="1">
    <thead>
        <tr>
            <th class="first" style="width:120px">
                Operating System </th>
            <th class="">
                Percentage </th>
        </tr>
    </thead>
    <tbody>

        <tr>
            <td class="">iOS 8.4</td>
            <td class="">
                <div class="ui-percentage" style="width:17%">17 %</div>
            </td>
        </tr>

        <tr class="tr even">
            <td class="">iOS 8.3</td>
            <td class="">
                <div class="ui-percentage" style="width:6%">6 %</div>
            </td>
        </tr>

        <tr>
            <td class="">iOS 8.2</td>
            <td class="">
                <div class="ui-percentage" style="width:11%">11 %</div>
            </td>
        </tr>

        <tr class="tr even">
            <td class="">iOS 8.1.3</td>
            <td class="">
                <div class="ui-percentage" style="width:11%">11 %</div>
            </td>
        </tr>

        <tr>
            <td class="">iOS 8.1</td>
            <td class="">
                <div class="ui-percentage" style="width:6%">6 %</div>
            </td>
        </tr>
    </tbody>
</table>

当页面第一次加载时,我希望折叠表格。当我单击“切换”按钮时,我想更改表状态,因此基本上是在再次单击该按钮时展开它并再次折叠它。

这是我的脚本

<script>
    $(document).ready(function() {
        $('.toggle-btn').closest('table').hide(); // I want to target the table right after the button
        $('.toggle-btn').on('click', function(event) {
            $(this).closest('table').toggle();
        });
    });
</script>

我怎样才能使这项工作正确?

最佳答案

为什么不直接使用切换功能呢?

$(document).ready(function() {
    $('table').hide();
    $('.toggle-btn').on('click', function() {
        $('table').toggle();
    });
});

关于javascript - jQuery - 切换按钮显示/隐藏表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35174536/

相关文章:

javascript - 替换内容后如何触发 jQuery .click()?

Javascript 变量,设置为 HTML 对象,总是返回 null

javascript - 抓取选定的<按钮>

javascript - 如何隐藏视频元素后面的 div?

javascript - 使用对象数组中的两个值更新 HTML

asp.net - 如何从 javascript 从 asp.net 文本框中检索值?

javascript - 将驼峰式字符串转换为带连字符的 Angular 服务

Javascript 每个 tr 中的最高数字,跳过 3 列

javascript - 在随机 JavaScript 函数之后获取输入字段的值

php - 在 DIV 中居中内容(动态输出/文本)