4

引导文档说,您可以使用以下代码轻松禁用数据 API:

$('body').off('.data-api');

当其他 javascript 使用相同的数据属性时,我认为这在某些情况下真的很酷。您只需在特殊区域中禁用 bootstrap-API。

例如在每个 a-Tag 中禁用 API:

<html>
  <head>
    <title>Bootstrap - Test - Disable The API</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script>
      $(document).ready(function() {
        //This is working: $(document).off('.data-api');

        //This is not working:
        $('a').off('.data-api');
      });
    </script>
  </head>
  <body>

    <!-- Button to open the modal -->
    <a id="clickBtn" href="#myModal" data-toggle="modal">Launch demo modal</a>

    <!-- Modal -->
    <div id="myModal" class="modal hide fade">
      This is just a little test
    </div>

  </body>
</html>

但它没有用。

还有一个clickEvent用于模态的。谁能告诉我我做错了什么?

它对任何一个都不起作用$('#clickBtn').off('.data-api');

4

3 回答 3

4

好的,我想我自己解决了这个问题。Bootstrap 将事件处理程序附加到文档根:

  $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
      ...
  })

当然你不能用

$('body').off('.data-api');或者$('#clickBtn').off('.data-api');

因为处理程序附加到文档根而不是正文或元素本身。

如果要禁用特殊元素的 API(在我的示例中为 a-Tag),则必须从 off-method 定义选择器参数:

$(document).off('.data-api','a');

似乎引导文档有点令人困惑......

于 2013-02-16T10:08:56.393 回答
1

以下代码不起作用:

$(document).off('.data-api','a');

您只能像这样禁用单个插件。

e.g. $(document).off('.modal.data-api');

不是 html 元素。

但是,您可以使用 jQuery 覆盖导致引导数据属性与来自其他脚本的数据属性冲突的问题。使用您的链接示例,以下操作可以使链接变得不可点击,该元素具有来自非引导插件的脚本的数据属性:

$('.selected-areas a').filter('[href]').click(function(){
    window.location.href = $(this).attr('href');
});
于 2014-04-04T00:43:31.133 回答
1

如果您只想在 DOM 树的特定部分下使用 Bootstrap 的数据 API,您可以尝试将事件处理程序移动到其他一些共同的祖先。这段代码对我来说效果很好,但请注意 -如此处所述-这种方法使用未记录的 jQuery 功能来获取分配给object的事件处理程序document

function moveBootstrapEventHandlersTo(target) {
    /* undocumented jQuery feature below */
    var eventHandlers = $._data(document, "events");

    $.each(eventHandlers, function() {
        $.each(this, function() {
            $(target).on(
                this.origType + "." + this.namespace,
                this.selector,
                this.data,
                this.handler
            );
    });
});

您现在可以默认禁用数据 api 并使用一些类名启用它。记住不要嵌套这些元素。所有事件都在冒泡,所以 - 当嵌套时 - 同一个事件处理程序被多次调用。

<body>
    <div class="with-bs-data-api">
        // bootstrap data api works here
    </div>
    <div class="some-other-class">
        // but doesn't work here
    </div>
    <footer>
        <div class="with-bs-data-api">
            // and here it works again
        </div>
    </footer>
    <script type="text/javascript">
        moveBootstrapEventHandlersTo(".with-bs-data-api");
        $(document).off('.data-api');
    </script>
</body>
于 2016-06-19T11:48:18.723 回答