在jQuery中实现Bootstrap模态框按钮变量跨函数传递
解决Bootstrap模态框关闭时显示对应按钮名称的问题
嘿,作为JS新手遇到这种变量传递的问题太正常了,我来帮你捋清楚问题出在哪,再给你俩靠谱的解决方案!
首先咱们先揪出你现有代码的两个关键问题:
hidden.bs.modal事件的回调参数不是你想要的recipient,而是事件对象,所以你现在的alert其实是在拼接一个事件对象,肯定显示不对;show.bs.modal里的return String(recipient)完全没用,事件处理函数的返回值不会被其他事件处理函数捕获,这就是你之前尝试传递变量失败的核心原因。
接下来给你两种简单可行的方案:
方案1:把收件人信息存在模态框的data属性里
这种方法最贴合Bootstrap的使用习惯,把需要传递的值直接绑定到模态框元素本身:
$(document).ready(function() { $("#exampleModal").on('show.bs.modal', function(e) { var button = $(e.relatedTarget); var recipient = button.data('name'); var modal = $(this); modal.find('.modal-title').text('New message to ' + recipient); // 把收件人信息存到模态框的自定义data属性里 modal.data('current-recipient', recipient); }); $('#exampleModal').on('hidden.bs.modal', function() { // 从模态框的data属性里取出收件人信息 var recipient = $(this).data('current-recipient'); // 顺便纠正个小拼写:send的过去分词是sent不是sended哦😉 alert('You haven\'t sent the message to ' + recipient); }); });
方案2:用闭包变量存储收件人信息
因为$(document).ready()的回调函数是一个闭包,里面定义的变量可以被内部的两个事件处理函数直接访问,既不会污染全局作用域,又能轻松传递值:
$(document).ready(function() { // 在闭包里定义变量,两个事件处理函数都能访问到 let currentRecipient; $("#exampleModal").on('show.bs.modal', function(e) { var button = $(e.relatedTarget); currentRecipient = button.data('name'); var modal = $(this); modal.find('.modal-title').text('New message to ' + currentRecipient); }); $('#exampleModal').on('hidden.bs.modal', function() { // 确保有收件人信息再弹出提示 if (currentRecipient) { alert('You haven\'t sent the message to ' + currentRecipient); } }); });
这两种方案都能完美实现你的需求:点击不同按钮打开模态框,关闭时弹出对应按钮的data-name信息。
内容的提问来源于stack exchange,提问作者Luca Ribezzo
相关产品推荐
相关产品推荐

