javascript - Bootstrap 切换不起作用

标签 javascript jquery html twitter-bootstrap

我有这个 HTML:

<table class="itemsTable table table-striped table-condensed table-hover">
    <thead>
    <tr>
        <th>#</th>
        <th>Location</th>
    </tr>
    </thead>
    <tbody>

    <tr class="collapse">
        <td class="center">1</td>
        <td>
            <a href="locations?location_id=1">Title 1</a>
        </td>
    </tr>

    <tr class="collapse">
        <td class="center">2</td>
        <td>
            <a href="locations?location_id=2">Title 2</a>
        </td>
    </tr>

    <tr class="collapse">
        <td class="center">3</td>
        <td>
            <a href="locations?location_id=3">Title 3</a>
        </td>
    </tr>

    </tbody>
</table>
<a href="#" class="collapseBtn">test</a>

和 jQuery:

$('.collapseBtn').on('click', function(e) {
    e.preventDefault(); 
    var $this = $(this);
    var $collapse = $this.closest('.itemsTable').find('.collapse');
    $collapse.collapse('toggle');
});

我希望行在链接点击时显示/隐藏行为。怎么了?

最佳答案

$.closest 将在 dom 树中查找匹配元素 - .itemsTable 不是 .collapseBtn 的父级 - 所以 $this.closest('.itemsTable') 不会匹配任何元素。

所以,要么将 .collapseBtn 放在表格中,要么使用 $this.prev() 而不是 $this.closest('.itemsTable' )

您可以通过在控制台中运行 $('.collapseBtn').closest('.itemsTable') 来测试是否存在匹配的元素

关于javascript - Bootstrap 切换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18878465/

相关文章:

html - 在我的导航中添加我的 Logo

java - 如何用正则表达式截取URL

javascript - 如果我有一串 HTML 代码,如何使用 JQuery 来解析它?

javascript - 缩放(中心) map 到 OpenLayers 3 中的标记

javascript - 缩放功能

javascript - AngularJs Select通过PHP生成

javascript - jQuery 使用 "subquery"

javascript - 将输入值与数据库 Coldfusion 中的值进行比较

javascript - 尝试将 VAR 设置为 DIV 的名称

javascript - Jquery - 每个父元素,删除并克隆子元素