[英]Bootstrap toggle doesn't work
我有这个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的父.collapseBtn
-因此$this.closest('.itemsTable')
将不匹配任何元素。
因此,可以将.collapseBtn
放在表中,或者使用$this.prev()
代替$this.closest('.itemsTable')
。
您可以通过在控制台中运行$('.collapseBtn').closest('.itemsTable')
来测试是否存在匹配的元素
从130918_1100PST开始,所选答案不正确。 尽管作者正确地确定了为什么closest()
选择器将不返回任何要折叠的元素,但仅此一项并不能解决OP的问题。
这个选择也将用于选择元素塌陷工作:
$('.collapse').methodgoeshere();
但元素不会展开/折叠-不仅仅是使用的选择器。
用户Chad在benjaminbenben的答案下面的jsFiddle中确定了解决该问题的关键,实际上是使用了错误的方法。
这不起作用:
selector.collapse('toggle');
这样做:
selector.toggle();
因此,正确的答案是:
$('.collapseBtn').on('click', function() {
$('.collapse').toggle();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.