【发布时间】:2015-10-29 18:05:39
【问题描述】:
我正在尝试使用 jquery 切换表中的隐藏行。此外,我想在单击图标时将字形图标的状态从加号更改为减号(反之亦然)。出于某种原因,我遇到了类选择器的问题。当我从加号图标转到减号图标时,它工作正常。但是,我不能从减号图标转到加号图标。 jquery click hook 仍在处理错误的函数。
这里是 jsfiddle http://jsfiddle.net/gs4te89g/
HTML:
<table id="table" class="table table-hover table-striped" style="margin-top: 0px;">
<thead>
<tr>
<th class="detail" rowspan="1"><div class="fht-cell"></div></th>
<th style="" data-field="id" tabindex="0"><div class="th-inner ">Item ID</div>
<div class="fht-cell"></div></th>
<th style="" data-field="name" tabindex="0"><div class="th-inner ">Item Name</div>
<div class="fht-cell"></div></th>
<th style="" data-field="price" tabindex="0"><div class="th-inner ">Item Price</div>
<div class="fht-cell"></div></th>
</tr>
</thead>
<tbody>
<tr data-index="0">
<td><a class="detail-icon" href="javascript:"><i class="glyphicon glyphicon-plus icon-plus" id="1"></i></a></td>
<td style="">0</td>
<td style="">Item 0</td>
<td style="">$0</td>
</tr>
<tr id="detail-view1" style="background-color:yellow;display: none;">
<td colspan="4">My Hidden Row</td>
</tr>
</tbody>
和javascript:
$('.glyphicon.glyphicon-plus').on('click', function (e) {
e.preventDefault();
$(this).removeClass('glyphicon-plus icon-plus');
$(this).addClass('glyphicon-minus icon-minus');
$('#detail-view'+this.id).toggle('slow');
});
$('.glyphicon.glyphicon-minus').on('click', function (e) {
e.preventDefault();
$(this).removeClass('glyphicon-minus icon-minus');
$(this).addClass('glyphicon-plus icon-plus');
$('#detail-view'+this.id).toggle('slow');
});
【问题讨论】:
-
将
$('.glyphicon.glyphicon-minus').on('click', function (e) {})视为两部分:(1) 检索$('.glyphicon.glyphicon-minus')元素,(2) 将点击事件绑定到它们。当页面加载并运行脚本时,有多少个$('.glyphicon.glyphicon-minus')元素? -
只需使用
toggleClass。 jsfiddle.net/g161ppg6/1 -
其他答案(包括委托或类检查)正在解决一个您不需要解决的更复杂的问题。
标签: jquery