jQuery 插件 .fn 问题 [英] jQuery plugin .fn question

查看:15
本文介绍了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.

另一个值得关注的地方是各种社交编码网站(GitHubBitBucketGoogle 代码等)和搜索jQuery Plugin"看看其他人是怎么做的.

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.

这篇关于jQuery 插件 .fn 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆