What is wrong with this syntax?
<script>
jQuery(function() {
jQuery.fn.myfunction(myparam) {
alert(myparam);
return 0; // return jQuery?
}
my开发者_高级运维function('Hello World');
});
</script>
I'm trying to learn how to extend jQuery.
jQuery.fn.myfunction(myparam) {
should be
jQuery.fn.myfunction = function(myparam) {
as you are assigning the property myfunction
of object jQuery.fn
a value of function () {...
Your syntax is trying to call a method called myFunction
on the jQuery.fn
reference.
To extend the jQuery object, you want this syntax:
<script>
jQuery(function() {
jQuery.fn.myfunction = function(myparam) {
alert(myparam);
return this; // returns the current jQuery object.
}
// Select something with jQuery using the $() function here.
$().myfunction('Hello World');
});
</script>
A method defined via jQuery.myFunction is a "static" function. You call it by doing $.yourFunction, and it's not tied to a result set.
Conversely, a function defined on jQuery.fn.myFunction is a tied to a result set; if you do "this" within that function, you'll get the jQuery object that was used to call it. In other words, if you do $("P").myFunction() "this" in my Function will be $("P").
From the documentation...
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
See more here.
精彩评论