歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery中為防止庫沖突命名的辦法

jQuery中為防止庫沖突命名的辦法

日期:2017/3/1 10:37:12   编辑:Linux編程

在jQuery中,如果也同時引入了其他js庫,而其他庫也用了$符號的話,則會產生沖突,
為了防止這種情況的發生,可以使用noconflict進行避免,代碼如下:

<script type="text/javascript" src="otherLib.js"></script>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

$.noConflict();

// 使用其他js庫的代碼
</script>

同時,也可以自定義自己的命名項目命名空間,比如項目為abc,可以這樣:
ABC('contentArea').show(),而不是只使用$('contentArea').show()
當然,也有方法可以繼續在jquery代碼中,在沖突的時候使用$符號,可以在
ready事件中繼續寫:
jQuery(document).ready(function($) {

// 這裡繼續寫$符號的代碼.

});

也可以簡寫為:
jQuery(function($){

//...............
});

總的寫法如下,當跟其他庫一起用的時候:
<script type="text/javascript" src="otherLib.js"></script>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

$.noConflict();

jQuery(function($) {

// jQuery code with $.

});

// 其他js庫代碼.

</script>

也可以再簡單點:
$.noConflict()(function(){

// jQuery code

});

// 其他js庫代碼.

Copyright © Linux教程網 All Rights Reserved