jQuery插件.fn问题

jQuery插件.fn问题

问题描述:

我似乎在创建jquery插件时遇到了一些问题.我正在Firebug控制台中测试一个简单的插件,但未按我的期望定义功能.这是我正在使用的代码模式

I seem to be having some problems creating a jquery plugin. I am testing a simple plugin in firebug console and the function is not being defined as I would expect. Here is the code pattern I am using

jQuery.fn.test = function () {console.log("runs")}

我试图通过此调用来调用该函数,但该调用不起作用.

I am trying to call the function with this call which is not working.

$.test()

但是这个电话确实有

$.fn.test()

我不认为这是应该工作的方式,所以我认为我做错了,尽管所有文档似乎都同意我应该是对的.有人有什么建议吗?

I don't think this is how it is supposed to work so I think I am doing something wrong, although all the documentation seems to agree that I should be correct. Any one have any advice?

谢谢, 科里

尝试$('div').test()

给出 http://docs.jquery.com/Plugins/Authoring 的内容jQuery插件的很好的介绍.

Give http://docs.jquery.com/Plugins/Authoring a read for a good introduction to jQuery plugins.

好的,这是我在这里的一些其他信息.创建插件时,存在三个接近的绝对规则:

Ok here's some additional info while I'm here. When creating a plugin there three near absolute rules:

  • 在定义插件时始终使用匿名方法,以确保使用$获取jQuery对象.
  • 始终尝试再次返回jQuery对象(用于链接).
  • 总是迭代元素,因为您的选择器可能匹配多个元素.
  • Always use an anonymous method when you define your plugin so you assure you get the jQuery object with $.
  • Always try to return the jQuery object again (for chaining).
  • Always iterate over elements since your selector likely matched more than one element.

因此,为了方便起见,请像这样开始:

So for convention's sake, start off like this:

(function($) {
  $.fn.test = function() {
    return this.each(function() {
      console.log("runs");
    });
  }
})(jQuery);

这将为选择器匹配的每个项目打印运行"(如果仅使用div,则很多).尝试放入$(this).css('background-color', 'red');并查看会发生什么.

This will print "runs" for every item matched by your selector (a lot if you use just div). Try putting $(this).css('background-color', 'red'); in and see what happens.

另一个值得一看的好地方是各种社交编码网站( GitHub Google代码等),以及搜索"jQuery插件"以查看其他人的行为.

Another good place to look would be various social coding sites (GitHub, BitBucket, Google Code, etc.) and search for "jQuery Plugin" to see how others are doing it.