-1

Newbie question please bear with me. I am following this tutorial. It illustrates how to write a very simple plugin. But may I ask how to use/call this plugin?

<script>
    function changeColor($obj, color) {  
        $obj.css({color : color});  
    }  

    $.fn.myPlugin = function(options) {  

        return this.each(function() {  
            var $this = $(this);  

            changeColor($this, options.color);          
        });  
    };
</script>
4

1 回答 1

3

jsFiddle

HTML

<div>Hello World!</div>

JavaScript(已包含 jQuery)

function changeColor($obj, color) {
    $obj.css({
        color: color
    });
}

$.fn.myPlugin = function (options) { 
    return this.each(function () {
        var $this = $(this);

        changeColor($this, options.color);
    });
};
$("div").myPlugin({
    color: "red"
});


这是一个完整的 HTML 代码结构:

<!doctype html>
<html>
  <head>
    <title></title>
  </head>

  <body>
    <div>Hello World!</div>

    <!-- Prepend http: in case you're working from the local file system -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function changeColor($obj, color) {
          $obj.css({
              color: color
          });
      }

      $.fn.myPlugin = function (options) { 
          return this.each(function () {
              var $this = $(this);

              changeColor($this, options.color);
          });
      };


      $("div").myPlugin({
          color: "red"
      });
    </script>
  </body>
</html>
于 2013-08-20T11:23:59.450 回答