js 小结

来源:互联网 发布:cnki是什么数据库 编辑:程序博客网 时间:2024/05/22 06:38

在 jQuery 中,fn 其实就是 JavaScript 中 propotype 的一个别名,$ 是 jQuery 的别名,所以$.fn.pluginName 等同于 jQuery.prototype.pluginName$.fn.pluginName 表示创建一个 jQuery 的属性,通俗的说是写一个 jQuery 函数pluginName 才是函数名实例$.fn.setRedText = function() { return $(this).css("color", "red");};$("p").setRedText();





 <body>
<p class="testp">asdf</p>
 </body>
 <script>
 $(function(){
  jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
var settings={validate:false,limit:5,name:"foo"};
var options={validate:true,name:"bar"};
jQuery.extend(settings,options);
alert(settings.validate+"  "+settings.limit+"  "+settings.name);
//alert(jQuery.max(6,3));
$.fn.extend({
alertWhileClick:function(){
$(this).click(function(){
alert($(this).text);
})
}
})
 })
 $(function(){
 $(".testp").alertWhileClick();
 })
 
 </script>
</html>




这个是jquery插件的形式,举个例子: <div id="myDiv"></div> (function($){  $.fn.extend({    test:function(){       alert($(this).attr('id'));    }})})(jQuery) $('#myDiv').test();打印出 : myDiv (function($){$.extend({test:function(){alert('111');}})})(jQuery)$.test();打印出:111



$.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效。 
如扩展$.fn.abc() 
那么你可以这样子:$("#div").abc(); 
通常使用$.extend()方法扩展.


$.fn是什么东西呢。查看jQuery代码,就不难发现。

jQuery.fn = jQuery.prototype = {

   init: function( selector, context ) {//.... 

};

原来 jQuery.fn = jQuery.prototype.对prototype肯定不会陌生啦。


0 0