2013-02-15 67 views
4

自舉documentation說,你可以很容易地與下面的代碼禁用數據API:禁用引導數據屬性API?

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

我想這對某些情況下,當其他的JavaScript使用相同的數據的屬性真的很酷。您只需要禁用特殊區域中的bootstrap-API。

例如禁用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

好吧,我想我自己解決了這個問題。 引導重視的事件處理程序的文檔根:

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

當然是因爲附加處理程序文檔根目錄,您不能停用與

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

的API而不是身體或元素本身。

如果要禁用一個特殊元素的API(在我的例子中,一個標籤),你必須定義從關方法選擇參數:

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

似乎引導-documentation是有點混亂...

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'); 
}); 
0

如果你想用引導的數據API只在某些部分你的DOM樹,你可以嘗試將事件處理程序移動到其他一些共同的祖先。此代碼適用於我,但請注意 - as stated here - 此方法使用未記錄的jQuery功能來獲取分配給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>