简体   繁体   中英

jquery very simple plugin, very basic

can we call jquery plugin like this? this is in my plugin file

    (function($) {

    $.fn.alertme=function(){
    alert('just testing');
    };


    }(jQuery));

i have included the plugin file ,, and calling the function on my home page...

    <script>
    $(document).ready( function() {

    alertme();
    });


    </script>

I see an error message on console log Uncaught ReferenceError: alertme is not defined i even tried return alert('just testing'); ,, how do we fix this?

You added the function to $.fn , which is an alias to the prototype of the jQuery constructor. That means your function is attached to all objects created as $(someArgs) .

Call your function on a jQuery object, for example

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

or

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

or even

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

But there's no point in making a jQuery plugin if you don't use this (the jQuery object) in the function. Usually you'd do something like this :

// logs all elements of the jQuery collection
$.fn.logme=function(){
  this.each(function(){
    console.log(this);
  })
};

$(document).ready( function() {
   $('p').logme();
});

You must call using jQuery object

Try this

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM