使用jQuery.noConflict();主要做用是在任什麼時候候,只要在jQuery加載後就能夠調用,將$符號的使用權返回給其它的js庫,jQuery在建立它本身的名字空間時就將其它庫的$保存在本身的一個變量當中。 javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<html>
<head>
<scriptsrc="prototype.js"></script>
<scriptsrc="jquery.js"></script>
<scripttype="text/javascript">
//各個js庫之間的主要衝突在於$的衝突,這個方法是用來處理這個問題的
jQuery.noConflict();
//本來使用jQuery代碼部分的$ 用jQuery替代
jQuery(document).ready(function (){
jQuery("div").hide();
});
// Use Prototype with $(...), etc.
$('proto').hide();
</script>
</head>
<body></body>
</html>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<html>
<head>
<scriptsrc="prototype.js"></script>
<scriptsrc="jquery.js"></script>
<scripttype="text/javascript">
//$j就至關於jQuery,名稱你能夠自主定義
var $j = jQuery.noConflict();
// Use jQuery via $j(...)
$j(document).ready(function (){
$j("div").hide();
});
// Use Prototype with $(...), etc.
$('proto').hide();
</script>
</head>
<body></body>
</html>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<html>
<head>
<scriptsrc="prototype.js"></script>
<scriptsrc="jquery.js"></script>
<scripttype="text/javascript">
jQuery.noConflict();
// Put all your code in your document ready area
jQuery(document).ready(function ($){
// 這樣你能夠在這個範圍內隨意使用$而不用擔憂衝突
$("div" ).hide();
});
// Use Prototype with $(...), etc.
$('proto' ).hide();
</script>
</head>
<body></body>
</html>
|
按照這樣的順序加載,就不存在其它js庫的$符號被jQuery佔用的問題。因此對其它的js庫的代碼能夠不做任何修改,照常使用$,而對 jQuery可使用jQuery來替代$.如: html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<html>
<head>
<scriptsrc="prototype.js"></script>
<scriptsrc="jquery.js"></script>
<scripttype="text/javascript">
// 使用 jQuery 用 jQuery(...)
jQuery(document).ready(function (){
jQuery("div" ).hide();
});
// 使用 Prototype 時,用 $(...),
$('someid' ).hide();
</script>
</head>
<body></body>
</html>
|
或者你不想寫jQuery這麼長的字符,你能夠經過另一種方法: java
1
|
var $j = jQuery;
|
來實現簡短一點的$j,這多是最好的辦法了。
不過,當你只想使用jQuery來寫代碼時,你能夠經過名字空間仍然使用$,即採用和jQuery源代碼同樣的方法: jquery
1
2
3
4
5
6
|
<scripttype="text/javascript">
(function($) {
/* 在這個名字空間內,你能夠隨意使用$符號來引用jQuery,只不過是其它$被jQuery使用,你不能使用prototype或其它的js庫
*/ }
)(jQuery)
</script>
|
參考來源:http://docs.jquery.com/Using_jQuery_with_Other_Libraries 程序員