1. ホーム
  2. ジャバスクリプト

[解決済み】ブートストラップ・モーダルオープンで関数を呼び出す

2022-04-12 17:28:26

質問

以前、JQuery UIのダイアログを使っていたのですが、そのダイアログには open オプションで、ダイアログが開かれたときに実行する Javascript コードを指定することができます。私はこのオプションを使って、私が持っている関数を使ってダイアログ内のテキストを選択していました。

今度は、bootstrapのモーダルを使ってそれをやってみたいと思います。以下はそのHTMlコードです。

<div id="code" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
        <pre>
print 'Hello World'

そして、モーダルを開くボタンについては

 <a href="#code" data-toggle="modal" class="btn code-dialog">Display code</a>

ボタンのonclickリスナーを使用しようとしましたが、アラートメッセージが表示されました。 以前 モーダルが表示される。

$( ".code-dialog" ).click(function(){
    alert("I want this to appear after the modal has opened!");
});

解決方法は?

を使用することができます。 表示イベント /show イベントは、必要なものに基づいています。

$( "#code" ).on('shown', function(){
    alert("I want this to appear after the modal has opened!");
});

デモの様子 プランカー

Bootstrap 3.0に対応したアップデート

Bootstrap 3.0でもshowedイベントを使用できますが、以下のように使用します。

$('#code').on('shown.bs.modal', function (e) {
  // do something...
})

Bootstrap 3.0のドキュメントはこちら の下にある「イベント"Event"」をご覧ください。