【问题标题】:Bootstrap-confirmation not binding to dynamic elements?引导确认不绑定到动态元素?
【发布时间】:2017-09-14 01:58:55
【问题描述】:

我有一个使用 AJAX 在页面上加载动态内容的表单。我还使用bootstrap-confirmation 来确认取消请求的功能。初次加载页面时确认有效。

这里是示例代码:

$(function() {

    $('[data-toggle=confirmation]').confirmation({
      rootSelector: '[data-toggle=confirmation]',
      popout: true
    });

    $(document).on('submit', '#some-form', function(e) {
      e.preventDefault();

      submitForm();
    });


    $('.static-element').on('click', '.cancel-request', function() {
      cancelRequest();
    });
}

.cancel-request 的点击事件对动态内容有效,但确认无效。我尝试将点击处理程序上的选择器更改为document,但这没有区别。我只是找不到将确认绑定回动态元素的方法。

我尝试在cancelRequest() 上创建回调,然后在其中重新初始化bootstrap-confirmation,但没有任何区别。我也尝试在 complete: 选项中重新初始化它,但这也不起作用。

我在其他几个 SO 答案中尝试了 Twitter BootStrap Confirmation not working for dynamically generated elements,但它们在我的情况下不起作用。

【问题讨论】:

  • 请创建一个有确切问题的jsfiddle
  • 我试过了,但我无法在 jsfiddle 中获得引导确认。尽管确认不起作用,但它仍然表现出相同的行为。如果您在单击之前检查按钮,则它已绑定到它,单击后则不是。 jsfiddle.net/6wrb01u6/6
  • 这里有一个解决方案 jsfiddle.net/6wrb01u6/7contentclass 而不是 id。将取消的点击事件更改为$('.content').remove();
  • 谢谢,但同样的问题仍然存在。 bootstrap-confirmation 在单击之前绑定到按钮,但之后不绑定。

标签: jquery twitter-bootstrap-3 event-delegation bootstrap-confirmation


【解决方案1】:

您的 JSfiddle 正在删除您将 JQuery 侦听器绑定到的元素。另一种方法是简单地操作您要替换的元素,这样您就不必与瞬态元素作斗争。

//from your JS fiddle at https://jsfiddle.net/6wrb01u6/6/
$('[data-toggle=confirmation]').confirmation({
  rootSelector: '[data-toggle=confirmation]',
  // other options
});

$('#replace').on('click', '.do-something', function() {
  var html = "content";
  $.ajax({
    url: "/echo/html/",
    type: "POST",
    data: html,
    dataType: "HTML",
    success: function(data) {
      $('#replace>span').removeClass('do-something').removeClass('btn-primary');
      $('#replace>span').addClass('cancel').addClass('btn-danger');
      $('#replace>span').html('Cancel');
      $('.content').remove();
      $('#replace').append('<p class="content">New content</p>');
    }
  });
});

$('#replace').on('click', '.cancel', function() {
  $('.content').remove();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2018-11-20
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2011-10-08
    相关资源
    最近更新 更多