我有一个交易表,我想为每行添加一个小按钮。单击后,将出现一个带有两个菜单项的小下拉列表,如下所示:
<ul id="contextMenu" class="dropdown-menu" role="menu" style="display:none" >
<li><a tabindex="-1" href="#">Pay</a></li>
<li><a tabindex="-1" href="#">Delete</a></li>
</ul>
但是,我的表可以有零行,甚至可能有几百行,因此重复执行代码,加上必须创建下拉菜单的按钮,将增加很多页面大小。
有没有一种方法可以一次拥有该代码,并且以某种方式从按钮单击中使用每一行中的相同代码?另外,我需要根据该行的ID更改每行的href值。因此href实际上是这样的:
\transaction\pay?id=10
随着每一行的ID更改。
最佳答案
像这样在您的行中添加一个按钮:
<td class="dropdown">
<a class="btn btn-default actionButton" data-toggle="dropdown" href="#">
Action
</a>
</td>
下拉菜单仅在打开它的
data-toggle
之后立即自动定位。为了避免编写大量定位代码,您可以在打开下拉菜单之前先将其移动://save the selector so you don't have to do the lookup everytime
$dropdown = $("#contextMenu");
$(".actionButton").click(function() {
//get row ID
var id = $(this).closest("tr").children().first().html();
//move dropdown menu
$(this).after($dropdown);
//update links
$dropdown.find(".payLink").attr("href", "/transaction/pay?id="+id);
$dropdown.find(".delLink").attr("href", "/transaction/delete?id="+id);
//show dropdown
$(this).dropdown();
});
Demo in jsFiddle