jQuery扩展与noConflict的用法-小示例

有时我们要用到自己定义的jquery,这时可以通过jQuery扩展来实现该功能

index.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6    <script src="jquery-3.1.0.min.js"></script>
 7    <script src="myjQuery.js"></script>
 8    <script src="Extends.js"></script>
 9 </head>
10 <body>
11      
12 </body>
13 </html>

 

自己定义的 myjQuery.js

$.myjq = function(){
    alert("hello myjQuery");
}

 

Extends.js

$(document).ready(function(){
    $.myjq();
});

最后打开浏览器后访问,成功输出 “hello myjQuery”

 

接下来介绍另一种比较常用的扩展方法:

index.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6    <script src="jquery-3.1.0.min.js"></script>
 7    <script src="myjQuery.js"></script>
 8    <script src="Extends.js"></script>
 9 </head>
10 <body>
11      <div></div>
12 </body>
13 </html>

自己定义的 myjQuery.js

$.fn.myjq = function(){
    $(this).text("hello");
}

Extends.js

$(document).ready(function(){
    $("div").myjq();
});

同样实现了效果

 

2、jQuery当前的美元符号如果被其它框架所占有时的处理方法

index.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6    <script src="jquery-3.1.0.min.js"></script>
 7    <script src="noConflict.js"></script>
 8 </head>
 9 <body>
10      <div>Hello</div>
11      <button id="btn">按钮</button>
12 </body>
13 </html>

 

noConflict.js

1 var myjq = $.noConflict();//当前的美元符号如果被其它框架所占有的时候,加上这句话,然后将美元符号换成myjq即可
2 myjq(document).ready(function(){
3     myjq("#btn").on("click",function(){
4         myjq("div").text("new hello");
5     });
6 });

很简单...

posted @ 2016-08-12 16:41  UniqueColor  阅读(195)  评论(0编辑  收藏  举报