开发者

I just don't understand $.fn in jQuery

开发者 https://www.devze.com 2022-12-14 04:15 出处:网络
What is wrong with this syntax? <script> jQuery(function() { jQuery.fn.myfunction(myparam) { alert(myparam);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消