如何在表格右键菜单中获取隐藏列的会员记录ID并用于详情跳转
解决方法:获取隐藏列ID并实现右键菜单跳转
Hey Rob, 完全可以实现你想要的功能!核心思路是在右键触发菜单时,先获取当前行的隐藏ID并暂存,然后在点击View选项时用这个ID拼接跳转链接。下面是修改后的完整代码,我会标注关键修改点:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script> <ul class='custom-menu'> <li data-action="View">View</li> <li data-action="Renew">Renew</li> <li data-action="Amend">Amend</li> </ul> <!-- 假设你的会员表格结构类似这样(第一列隐藏) --> <table> <tr> <td style="display:none">12345</td> <td>会员A</td> <!-- 其他列... --> </tr> <tr> <td style="display:none">67890</td> <td>会员B</td> <!-- 其他列... --> </tr> </table> </body> </html> <script> // 用来暂存当前行的会员ID(也可以用菜单的data属性,两种方式都可以) let currentMemberId = ''; // Trigger action when the contexmenu is about to be shown $(document).bind("contextmenu", function (event) { // Avoid the real one event.preventDefault(); // 关键修改:获取当前右键点击行的隐藏ID // closest('tr')找到点击元素所在的表格行,find('td:first')定位到第一列 currentMemberId = $(event.target).closest('tr').find('td:first').text().trim(); // Show contextmenu $(".custom-menu").finish().toggle(100). // In the right position (the mouse) css({ top: event.pageY + "px", left: event.pageX + "px" }); }); // If the document is clicked somewhere $(document).bind("mousedown", function (e) { // If the clicked element is not the menu if (!$(e.target).parents(".custom-menu").length > 0) { // Hide it $(".custom-menu").hide(100); } }); // If the menu element is clicked $(".custom-menu li").click(function(){ // This is the triggered action name switch($(this).attr("data-action")) { // A case for each action. Your actions here case "View": // 关键修改:用暂存的ID拼接跳转链接 window.open(`https://url/memb-details-all/${currentMemberId}`); break; case "Renew": alert("Renew"); break; case "Amend": alert("Amend"); break; } // Hide it AFTER the action was triggered $(".custom-menu").hide(100); }); </script>
关键说明:
- 获取ID的逻辑:
$(event.target).closest('tr')会向上遍历DOM找到当前点击元素所属的表格行,不管你点击的是行内的哪个单元格,都能精准定位到目标行;然后find('td:first')就拿到了第一列(隐藏列)的内容,也就是会员ID。 - ID的暂存:这里用了一个全局变量
currentMemberId来存储,你也可以选择把ID存在右键菜单的data属性里(比如$(".custom-menu").data('memberId', currentMemberId)),两种方式都能实现需求。 - URL拼接修正:原来的代码里URL拼接有语法错误,我改用了ES6的模板字符串(反引号包裹,
${变量}插入值),这样拼接更清晰不易出错。
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

