【问题标题】:Extending jQuery is not working...?扩展 jQuery 不起作用...?
【发布时间】:2014-03-14 15:29:34
【问题描述】:

我不知道如何扩展 jQuery... 我有以下代码:

jQuery.fn.extend({

    whatever : function () {
        alert('yeah');
    }

});

哪个应该给我一个$.whatever 函数,不是吗?但是当我检查它或尝试运行它时:zilch。

看看这个小提琴: http://jsfiddle.net/66gpf/

checked the docs 对我来说似乎很好......所以,我做错了什么?

【问题讨论】:

  • 你需要使用$('body').html( typeof $('body').whatever );,因为它没有添加whatever作为jQuery静态对象的属性 - jsfiddle.net/arunpjohny/3XKLM/1
  • 天啊!想将其发布为答案,以便我将其标记为正确吗?
  • jQuery.whatever = function() { alert('yeah') };

标签: javascript jquery


【解决方案1】:

jQuery.fn 是对jQuery.prototype 的引用。因此,当您执行jQuery.fn.extend 时,您将属性添加到prototypenot 到 jQuery 本身。 whatever 函数将存在于所有 jQuery 实例上。

jQuery.fn.extend({
    whatever : function () {
        alert('yeah');
    }
});

$('#a_selector').whatever();

文档:http://api.jquery.com/jquery.fn.extend/

附:如果您希望函数以$.whatever 的形式存在而不是仅在 jQuery 对象实例上存在,请将其添加到 $ 而不是 $.fn

jQuery.extend(jQuery, {
    whatever : function () {
        alert('yeah');
    }
});

$.whatever();

【讨论】:

    【解决方案2】:

    您需要使用$('body').html( typeof $('body').whatever );,因为它不会将任何内容添加为 jQuery 静态对象的属性

    $('body').html(typeof $('body').whatever);
    

    演示:Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2023-03-11
      • 1970-01-01
      • 2013-12-28
      相关资源
      最近更新 更多