jQuery.fn.extend() 與 jQuery.extend()

jQuery.fn如何擴展。html

jQuery插件 $.fn(object)與$.extend(object)jquery

jQuery提供了兩個方法幫助開發插件函數

  • $.extend(object);擴展jQuery類自己;
  • $.fn.extend(object);擴展jQuery對象;

1、$.fn

$.fn 等於 $.prototype;這樣就好理解了,就比如對String.porotype增長一個函數,而後全部的字符串對象都可以直接調用,
jQuery也是若是。給jQuery增長一個函數,而後全部的jQuery對象都可以調用。jQuery對象就是$("#id")或
$(document.getElementById("Id"))這些;
在寫法上能夠
$.fn或$.fn.extend({})
this

<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>

     $.fn.clear = function(){
          $(this).html('');	//寫法一
      }
        
	$.fn.extend({
          clear:function(){
             $(this).html('');	//寫法二
          }
    })
            
    $(function(){
        $("#btn1").click(function(){
        	$("h1").clear();
        })
    	
    })
</script>
</head>
<body>

<h1>個人第一個 JavaScript 程序</h1>
<input type="button" id="btn1" value="肯定" />
</body>
</html> 

2、$.extend();

咱們知道$就是jQuery對象。因此
$.extend其實就是擴展"jQuery"這個對象自己的函數。實際上至關於你建立了一個object對象,而後object.abc = function(){}spa

<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
     $.clear = function(obj){
          obj.html('');			//寫法一
      }
        
	$.extend({
          clear:function(obj){
             obj.html('');		//寫法二
          }
    })
            
    $(function(){
        $("#btn1").click(function(){
        	$.clear($("h1"));
        })
    })
</script>
</head>
<body>

<h1>個人第一個 JavaScript 程序</h1>
<input type="button" id="btn1" value="肯定" />
</body>
</html> 
相關文章
相關標籤/搜索