8.2.5 基于事件源改变对话框内容
由于Bootstrap
支持为对话框事件绑定事件监听函数,而且可通过事件对象来获取触发对话框的事件源,因此我们就可以根据触发对话框的事件源来改变对话框内容。
程序示例
例如如下代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| <!DOCTYPE html> <html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> 根据事件源改变对话框内容 </title> <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="../bootstrap/css/bootstrap-theme.min.css"> </head>
<body> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-who="crazyit"> 发送信息给crazyit </button> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-who="fkjava"> 发送信息给fkjava </button> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-who="fkit"> 发送信息给fkit </button> <div class="modal" tabindex="-1" role="dialog" id="myModal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button class="close" type="button" data-dismiss="modal"> <span aria-hiden="true">×</span> </button> <h4 class="modal-title"></h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="recipient-name" class="control-label">收信人</label> <input type="text" class="form-control" id="recipient-name"> </div> <div class="form-group"> <label for="message-text" class="control-label">消息内容</label> <textarea class="form-control" id="message-text"></textarea> </div> </form> </div> <div class="modal-footer"> <button class="btn btn-default" type="button" data-dismiss="modal"> 关闭</button> <button class="btn btn-primary" type="button">保存</button> </div> </div> </div> </div> <script type="text/javascript" src="../jquery-3.1.1.js"></script> <script type="text/javascript" src="../bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript"> $('#myModal').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); var recipient = button.data('who'); var modal = $(this) modal.find('.modal-title').text('向' + recipient + "发送新信息") modal.find('.modal-body input').val(recipient) }); </script> </body>
</html>
|
上面代码定义了3个按钮用于触发对话框,不管用户单击哪个按钮都会打开对话框。
当用户打开对话框时,代码将会获取按钮上设置的data-who
属性值,然后在事件监听器中通过data-who
属性值修改对话框的内容。
原文链接: 8.2.5 基于事件源改变对话框内容