LoginSignup
7
5

More than 5 years have passed since last update.

bootstrapのpopoverを動的要素に対して使う

Posted at

Ajaxなどで動的に追加された要素に対してbootstrap3のpopoverのコンテンツを書き換えながら対応する方法を紹介します。

方法

popoverのcontentは、文字列または関数を渡すことができます。関数を渡せるので、動的に表現したい場合はそれを使います。

coffeescript
$ ->
  $(document).popover(
    html: true,
    selector: '.target-element',
    content: ->
      id = $(this).data('id') # button.target-element data-id="1"のdata-idから値を取得
      """
      <a class='btn btn-default btn-sm' href='#{Routes.favorite_hoge_path(id)}'>お気に入りに登録</a>
      """
    trigger: 'focus',
    delay: { show: 100, hide: 100}
  )

target-elementクラスを持つ要素全てを対象として、クリックされたら、クリックされた要素から値を取得し(ここでは$(this).data('id')とか)、そこからpopoverの内容を組み立てます。
このようにすると要素が追加される度にイベントを設定しなくてもよいので、短く書くことができます。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5