如何将参数传递给bootstrap popover内容中的按钮单击功能?

时间:2016-08-02 18:31:48

标签: javascript jquery html twitter-bootstrap

我有一个盒子对象列表,我正在制作每个盒子对象都有一个弹出窗口。我在弹出窗口中添加了一个按钮,我正在尝试为按钮设置click事件功能。 click函数show调用我的showBox(box)函数,该函数接受参数box。如何将此box参数传递给弹出窗口内的按钮?这是我现在的代码:

var tabindex = 0;
box_resources.forEach(function(box) {
    var title = truncateTitle(box.title);
    var title_button = '<a tabindex="' + tabindex + '" class="box-title-item btn btn-primary btn-xs" role="button" data-trigger="focus" style="margin:5px" data-toggle="popover">' + title + '</a>';
    var $list_item = $(title_button);

    $("#coverages-master-list").append($list_item);

    var show_box_button = '<a class="btn btn-primary" role="button">' + box.title + '</a>';

    $list_item.popover({
        html: true,
        placement: 'top',
        title: box.title,
        content: '<p>' + show_box_button + '</p>',
        trigger: 'focus'
    });

    tabindex++;

});

如何为click绑定show_box_button事件,如何让它调用我的showBox(box)函数,该函数接受参数box?谢谢!

以下是jsfiddle链接。

1 个答案:

答案 0 :(得分:1)

您可以使用popover .on('shown.bs.popover'...事件将点击事件添加到当前的弹出式按钮

  

请务必在.one('click'...使用.on('click'...

然后使用showBox数组调用box_resources函数,添加当前元素的tabindex

&#13;
&#13;
$(function () {

  var $coveragesMasterList = $("#coverages-master-list");

  var showBox = function(box) {
    console.log(box.title);
  }

  var box_resources = [
    { title: 'Box A' },
    { title: 'Box B' },
    { title: 'Box C' },
    { title: 'Box D' },
    { title: 'Box E' }
  ];

  var tabindex = 0;
  box_resources.forEach(function(box) {
    var title_button = '<a tabindex="' + tabindex + '" class="box-title-item btn btn-primary btn-xs" role="button" data-trigger="focus" style="margin:5px" data-toggle="popover">' + box.title + '</a>';

    var $list_item = $(title_button);

    $coveragesMasterList.append($list_item);

    var show_box_button = '<a class="btn btn-default btn-xs" role="button">' + box.title + '</a>';

    $list_item.popover({
      html: true,
      placement: 'top',
      title: box.title,
      content: '<p>' + show_box_button + '</p>',
      trigger: 'focus'
    });

    $list_item.on('shown.bs.popover', function () {
      var boxIndex = $(this).attr('tabindex');
      var $crntPopOver = $(this).next();
      var $crntPopOverBtn = $crntPopOver.find('.btn-default');
      $crntPopOverBtn.one('click', function() {
        showBox(box_resources[boxIndex]);
      })
    })

    tabindex++;
  });
});
&#13;
@import url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css');
body {
  margin-top: 100px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="coverages-master-list" style="display:inline-block; height:150px; overflow-y: auto"></div>
&#13;
&#13;
&#13;