I'm sure this is something simple, but I'm missing it - why does the following inside of a <script>
tag not work and pop up an alert?
jQuery.fn.extend({
sayHi: function () {
alert('hello!');
}
});
$(document).ready(function () {
jQuery.sayHi();
});
fn. extend() method extends the jQuery prototype ( $. fn ) object to provide new methods that can be chained to the jQuery() function.
fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn. something = function{}
This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object. Parameters: The extend() method accepts four parameter that is mentioned above and described below: deep: This parameter is the merge becomes recursive . target: This parameter is the object to extend.
Because you set jQuery.fn.sayHi
, not jQuery.sayHi
(which is undefined
, hence you get a runtime error).
Methods you set on jQuery.fn
are available on selections (jQuery objects) only, not the jQuery
function.
jQuery('body').sayHi();
would work.
For more information about plugin development, see http://learn.jquery.com/plugins/basic-plugin-creation/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With