繁体   English   中英

JS $('x')。myfunction不是函数

[英]JS $('x').myfunction is not a function

我很想知道导致功能“不存在”的原因是什么。
例如,我有以下内容:

$.fn.myfunction = function(options){
  alert("test");
};
  $("#hello").myfunction();
alert($.fn.myfunction instanceof Function);

为什么FireBug会记录它不是功能?

提前致谢。

编辑:
我想列出所有可能成为错误原因的可能性。 这不是我遇到的错误,但我只是想扩大视野并意识到更多可能性。

设置$.fn.myfunction可使myfunction函数可用于$(selector)返回的对象,而不是$本身。

因此, $("#hello").myfunction是一个函数,但$.myfunction不是。 如果由于某些原因您确实希望$.myfunction成为函数(例如,它是一个不需要jQuery对象列表即可操作的实用程序函数),只需将其显式设置即可,而无需使用$.fn

$.myfunction = function() { .... }

上下文中的$是什么? jQuery也许? 如果您使用的是jQuery,请这样标记您的问题。

(function( $ ) {
  $.fn.myPlugin = function() {

    return this.each(function() { // Maintaining chainability

      var $this = $(this);

      // Do your awesome plugin stuff here
      console.log($this); // TEMP

    });

  };
})( jQuery );

用法: $('#hello').myPlugin();

查看有关jQuery插件创作的更多信息。

添加括号似乎有效:

alert($().myfunction instanceof Function);

返回true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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