我有一个交易表,我想在每一行添加一个小按钮。单击时,会出现一个带有两个菜单项的小下拉菜单,如下所示:
<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都在变化。
答案 0 :(得分:3)
为您的行添加一个按钮,如下所示:
<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();
});
答案 1 :(得分:0)
感谢KyleMit:
对于任何喜欢使用html5数据元素而不是行ID的人。
改变这个....
<td class="dropdown">
<a class="btn btn-default actionButton" data-toggle="dropdown" href="#" data-iteration-id="${current.id}" data-some-other-thing="someOther.thing">
Action
</a>
</td>
然后你的菜单在迭代之外:
<ul id="contextMenu" class="hiddenMenu dropdown-menu" role="menu" >
<li><a id="edit"><g:message code="default.button.edit.label"/></a></li>
<li><a id="delete" onclick="return
confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure?')}');">
<g:message code="default.button.delete.label"/></a></li>
</ul>
现在终于编写脚本:
<script>
$(function() {
$dropdown = $("#contextMenu");
$(".actionButton").click(function() {
var id = $(this).attr('data-iteration-id');
//var otherElement = $(this).attr('data-some-other-thing');
//var id = $(this).closest("tr").children().first().html();
$(this).after($dropdown);
$dropdown.find("#edit").attr("href", "${createLink(action: "edit")}/"+id);
$dropdown.find("#delete").attr("href", "${createLink(action: "delete")}/"+id);
$(this).dropdown();
});
});
</script>
这对我来说非常适合grails。再次感谢
答案 2 :(得分:0)
在“mousedown”而不是“click”上移动上下文菜单会在引导下拉菜单被触发之前移动元素。我目前无法确定它是否适用于移动设备。
$contextMenu = $("#contextMenu");
$(".day-context").on("mousedown",function() {
//move dropdown menu
$(this).after($contextMenu);
});