简体   繁体   English

引导程序切换不起作用

[英]Bootstrap toggle doesn't work

I have this HTML: 我有这个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>

And jQuery: 和jQuery:

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

I want rows show/hide behavior on link click. 我希望行显示/隐藏链接点击时的行为。 What is wrong? 怎么了?

$.closest will look up the dom tree for a matching element - the .itemsTable isn't a parent of .collapseBtn - so $this.closest('.itemsTable') won't match any elements. $ .closest将在dom树中查找匹配的元素-.itemsTable不是.collapseBtn的父.collapseBtn -因此$this.closest('.itemsTable')将不匹配任何元素。

So, Either put the .collapseBtn within the table, or use $this.prev() instead of $this.closest('.itemsTable') . 因此,可以将.collapseBtn放在表中,或者使用$this.prev()代替$this.closest('.itemsTable')

You can test if there are matching elements by running $('.collapseBtn').closest('.itemsTable') in the console 您可以通过在控制台中运行$('.collapseBtn').closest('.itemsTable')来测试是否存在匹配的元素

As of 130918_1100PST the selected answer is not correct. 从130918_1100PST开始,所选答案不正确。 Although the writer did correctly identify why the closest() selector would not return any elements to collapse, this alone did not fix the OP's problem. 尽管作者正确地确定了为什么closest()选择器将不返回任何要折叠的元素,但仅此一项并不能解决OP的问题。

This selector will also work for selecting the elements to collapse: 这个选择将用于选择元素塌陷工作:

$('.collapse').methodgoeshere();

but the elements won't expand/collapse -- it's not just a matter of the selector used. 但元素不会展开/折叠-不仅仅是使用的选择器。

The key to solving the problem, as user Chad identified in his jsFiddle below benjaminbenben's answer, is actually that the wrong method was used. 用户Chad在benjaminbenben的答案下面的jsFiddle中确定了解决该问题的关键,实际上是使用了错误的方法。

This did not work: 这不起作用:

selector.collapse('toggle');

This did: 这样做:

selector.toggle();

Therefore, the correct answer was: 因此,正确的答案是:

$('.collapseBtn').on('click', function() {
    $('.collapse').toggle();
});

jsFiddle here jsFiddle在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM