提问人:level42 提问时间:10/20/2017 最后编辑:Roblevel42 更新时间:10/20/2017 访问量:38
每个元素触发一次 Jquery 函数
Jquery firing function once per element
问:
因此,我有一个小表格,其中包含一些内容,只需单击一个按钮即可将其展开以显示包含额外内容的容器 div。
我正在尝试将函数与此操作绑定,但是当我这样做时,该函数似乎每行表数都会触发一次。
JSFiddle:
https://jsfiddle.net/jtby9c12/
桌子:
<button id="toggle-descriptions-button">+</button>
<table>
<tbody>
<tr>
<th class="table-header-1">Download</th>
<th class="table-header-2">Size</th>
<th class="table-header-3">Notes</th>
</tr>
<tr>
<td class="column-1">Item
<div class="div-container" style="display: block;">
<div class="div-gallery">
<img src="#">
<br style="clear: both">
</div>
<div class="div-description">Description Text</div>
</div>
</td>
<td class="column-2">1.2MB</td>
<td class="column-3">Note</td>
</tr>
</tbody>
</table>
*实际表格包含 22 行和描述,这仅显示结构示例。
Jquery:
var descriptions = $(".div-container")
var descButton = $("#toggle-descriptions-button")
descButton.click(function(){
console.log("Button Clicked!")
descriptions.toggle(400, function() {
console.log("I'm a fucntion!")
});
});
如您所见,它调用了该函数 22 次,而我试图让它只调用一次。
我希望获得函数的单个回调,这是所有描述的一个状态更改,我只需要一个返回。
答:
2赞
Rory McCrossan
10/20/2017
#1
为此,您可以使用从调用返回的。将事件处理程序附加到它,该处理程序将在解决所有 promise 后触发:promise()
toggle()
done()
var $descriptions = $(".div-container")
var $descButton = $("#toggle-descriptions-button")
$descButton.click(function() {
console.log("Button Clicked!")
$descriptions.toggle(400).promise().done(function() {
console.log("I'm a function!")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle-descriptions-button">+</button>
<table>
<tbody>
<tr>
<th class="table-header-1">Download</th>
<th class="table-header-2">Size</th>
<th class="table-header-3">Notes</th>
</tr>
<tr>
<td class="column-1">Item
<div class="div-container" style="display: none;">
<div class="div-gallery">
<img src="#">
<br style="clear: both">
</div>
<div class="div-description">Description Text</div>
</div>
</td>
<td class="column-2">1.2MB</td>
<td class="column-3">Note</td>
</tr>
<tr>
<td class="column-1">Item
<div class="div-container" style="display: none;">
<div class="div-gallery">
<img src="#">
<br style="clear: both">
</div>
<div class="div-description">Description Text</div>
</div>
</td>
<td class="column-2">1.2MB</td>
<td class="column-3">Note</td>
</tr>
<tr>
<td class="column-1">Item
<div class="div-container" style="display: none;">
<div class="div-gallery">
<img src="#">
<br style="clear: both">
</div>
<div class="div-description">Description Text</div>
</div>
</td>
<td class="column-2">1.2MB</td>
<td class="column-3">Note</td>
</tr>
</tbody>
</table>
评论
0赞
level42
10/20/2017
医 管 局!太棒了,这完全实现了我想要的。谢谢你指出这一点!
上一个:仅显示旋转图像的特定部分
下一个:调试日志记录 VB.net
评论