--- tags: Jquery, Bootstrap, Frontend --- # Bootstrap Modal傳遞資料 ## 創建基本modal ```htmlembedded= <button type="button" class="btn btn-outline-dark" data-toggle="modal" data-target="#exampleModal" data-id="example">點擊查看效果</button> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">取得資料</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <form method="POST" action=""> <input type="text" name="targetID" value=""> <button type="submit" class="btn btn-primary submit">送出</button> </form> <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button> </div> </div> </div> </div> ``` ## 點擊時傳遞data-id資料 ```javascript= $(function () { $('#exampleModal').on('show.bs.modal', function (e) { // 當點擊時取得data-id資料 var targetID = $(e.relatedTarget).data('id'); // 填入input $(e.currentTarget).find('input[name=targetID]').val(targetID); }); }); ``` ## 完整範例程式碼 <iframe height="300" style="width: 100%;" scrolling="no" title="Passing data to a bootstrap modal" src="https://codepen.io/joe94113/embed/gOGbxKV?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/joe94113/pen/gOGbxKV"> Passing data to a bootstrap modal</a> by 王冠智 (<a href="https://codepen.io/joe94113">@joe94113</a>) on <a href="https://codepen.io">CodePen</a>. </iframe>
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up