跨多个表行重用下拉菜单



我有一个事务表,我想在每一行添加一个小按钮。点击后,会出现一个带有两个菜单项的小下拉菜单,如下所示:

<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>

然而,我的表可以有0到潜在的数百行,所以重复的代码,加上按钮,必须创建下拉菜单,将是大量的页面大小增加。

是否有一种方法,有代码一次,不知何故,从按钮点击,从每一行使用相同的代码?此外,我需要根据每行的ID更改该行的href值。所以href应该是这样的:

transactionpay?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();
});

jsFiddle

Thanks To 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下非常适合我。再次感谢

For Bootstrap 5

在启动下拉菜单之前,用'mousedown'而不是'click'来移动上下文菜单。我现在还不能确定它是否能在手机上运行。

    $contextMenu = $("#contextMenu");
    $(".day-context").on("mousedown",function() {
      //move dropdown menu
      $(this).after($contextMenu);
    });

最新更新