【问题标题】:Twitter BootStrap Confirmation not working for dynamically generated elementsTwitter BootStrap Confirmation 不适用于动态生成的元素
【发布时间】:2015-07-20 03:02:13
【问题描述】:

我正在使用具有页面加载时生成的动态内容的 DataTable。 在表中,我使用了引导确认。 在脚本下面加载它。

$( document ).ajaxStop(function() {
    $(document).find('[data-toggle="confirmation"]').confirmation();
});

它会打开确认框,但是当单击“是”或“否”时,它不起作用。

这不起作用

我有以下代码来检测“确认”事件。

$(document).ready(function(){
    $(document).find('.delete-record').on('confirmed.bs.confirmation', function() {
        var thisEl = $(this);
        deleteForm($(this).attr('data-delid'));
    });
});

这是有效的

$(document).ajaxStop(function(){
    $(document).find('.delete-record').on('confirmed.bs.confirmation', function() {
        var thisEl = $(this);
        deleteForm($(this).attr('data-delid'));
    });
});

document.ready 有什么问题?

编辑:

我在其他页面上有与document.ready 相同的代码,但没有DataTable,它是HTML DIV 结构。

【问题讨论】:

  • .delete-record 元素是动态添加还是一直在页面上?
  • 第一次来自 PHP 脚本,在页面加载时 DataTable 会自动加载数据,因此它会在页面上响应。意味着总是在页面上。之前和之后。

标签: jquery ajax twitter-bootstrap document-ready confirmation


【解决方案1】:

尝试稍微更改您的事件绑定,以便使用备用 $.on 语法为每个现有和未来的 .delete-record 元素绑定。

$(document).ready(function(){
    $('body').on('confirmed.bs.confirmation', '.delete-record', function() {
        deleteForm($(this).attr('data-delid'));
    });
});

不知道您的页面结构,我选择绑定到body,但您可以将其绑定到表格的任何父元素。

【讨论】:

  • 天哪!我怎么忘了使用事件委托?每次我用这个,我只是没有注意到它。非常感谢。它有效,我已将其绑定到 document
  • 尽管采用了上面建议的事件绑定,但我似乎遇到了同样的问题。 jQuery 1.11.2 和 Bootstrap Confirmation 2.1.3 我的 jsfiddle jsfiddle.net/p98ajtbm/2
  • 我的问题实际上是弹出窗口根本没有显示。在生成新的 DOM 后重新启动插件使其工作jsfiddle.net/apphancer/2vvgq6yw
  • 我的问题有轻微差异,但deleteForm($(this).attr('data-delid')); 这条线打开了我的灯泡!!! :D :D 非常感谢。
【解决方案2】:

我认为是因为文档准备好后通过dom操作动态生成的元素

.delegate 代替.ready 怎么样?

$(document).delegate('.delete-record', 'confirmed.bs.confirmation', function() {
    deleteForm($(this).attr('data-delid'));
});

【讨论】:

  • 两者都是一样的,只是版本问题。在 1.4.3 中,委托存在,但在 1.7 以上的版本中,.delegate() 已被 .on() 方法取代。这与上面的正确答案相同。不过,谢谢指点。
【解决方案3】:

更简单的解决方案: 你有一个像

这样的初始化
$('[data-toggle="confirmation"][data-target="service"]').confirmation({});

在 $(document).ready(function(){}); 之前将 this 放入函数中 并在动态内容加载完毕后调用

function confirm(){
    $('[data-toggle="confirmation"][data-target="service"]').confirmation({
        your options come here
    });
}
$(document).ready(function(){
    confirm();
});

【讨论】:

    【解决方案4】:

    同样的问题...
    花点时间了解插件!
    很简单:

    my_new_dynamic_element.on('confirmed.bs.confirmation', function(){alert('ok')}).confirmation();
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      相关资源
      最近更新 更多