您的位置:首页 > Web前端 > JQuery

jquery插件编写以及调用

2011-09-08 15:57 375 查看
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>列表</title>

 <link type="text/css" href="xy.css" media="screen" rel="stylesheet" />

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

</head>

<body>

 <input class="w150 bgred" id="txt"/> <br/>

 <input type="button"  id="btn" value=" test "/>

</center>

</body>

<script type="text/javascript">

 <!--

 //在JQuery名称空间下申明一个名字

    $.fn.hilight = function(options) {    

    var defaults = {    

   foreground: 'red',    

   background: 'yellow'    

    };    

   

    //赋值操作

    var opts = $.extend(defaults, options);

   

   alert(defaults.foreground+"===>>");    

 };

 //调用

 $("#btn").hilight({foreground:'sdfsdfdsfd'});

    //接受options参数以控制插件的行为

 $.fnTest=function(options){

  options=$.extend({

   color:'red',

   font:'sf'

  });

  $.fnTest.make(options);

 };

 $.extend($.fnTest,{

   make:function(options){

   alert(options.color+"><+++>"+options.font);

   }

 });

 //调用

 $.fnTest.make({

  color:'blue',

  font:'sfsafsd'

 });

 

 

$.fn.hilight = function(options) {     

  var opts = $.extend({}, $.fn.hilight.defaults, options);    

};    

$.fn.hilight.defaults = {    

  foreground: 'red',    

  background: 'yellow'    

};     
现在使用者可以包含像这样的一行在他们的脚本里:  

//这个只需要调用一次,且不一定要在ready块中调用  
$.fn.hilight.defaults.foreground = 'blue';    
接下来我们可以像这样使用插件的方法,结果它设置蓝色的前景色:  

$('#myDiv').hilight();

 

// 创建一个闭包    

(function($) {    

  // 插件的定义    

  $.fn.hilight = function(options) {    

    debug(this);    

    // build main options before element iteration    

    var opts = $.extend({}, $.fn.hilight.defaults, options);    

    // iterate and reformat each matched element    

    return this.each(function() {    

      $this = $(this);    

      // build element specific options    

      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;    

      // update element styles    

      $this.css({    

        backgroundColor: o.background,    

        color: o.foreground    

      });    

      var markup = $this.html();    

      // call our format function    

      markup = $.fn.hilight.format(markup);    

      $this.html(markup);    

    });    

  };    

  // 私有函数:debugging    

  function debug($obj) {    

    if (window.console && window.console.log)    

      window.console.log('hilight selection count: ' + $obj.size());    

  };    

  // 定义暴露format函数    

  $.fn.hilight.format = function(txt) {    

    return '<strong>' + txt + '</strong>';    

  };    

  // 插件的defaults    

  $.fn.hilight.defaults = {    

    foreground: 'red',    

    background: 'yellow'    

  };    

// 闭包结束    

})(jQuery);

 -->

</script>

</html>

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息