[英]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.