jQuery插件创作 [英] jQuery Plugin Authoring

查看:90
本文介绍了jQuery插件创作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

知道为什么这个基本示例不起作用?

Any idea why this basic example doesn't work?

http://jsfiddle.net/Kq6pz/

(function( $ ){

  $.fn.testPlugin = function( options ) {  
        alert('hi');
  };
})( jQuery );

$.testPlugin();


推荐答案

因为您已将插件添加到 fn 命名空间不是 $ 命名空间。所以 $()。testPlugin()将起作用,但 $。testPlugin()不会。

Because you added your plugin to the fn namespace not to the $ namespace. So $().testPlugin() will work but $.testPlugin() does not.

如果你想污染 $ 命名空间,你可以这样做:

If you want to pollute the $ namespace you can do:

(function( $ ){

  $.testPlugin = function( options ) {  
        alert('hi');
  };
})( jQuery );

$.testPlugin();

我遵循的经验法则是:使用 $。当它不与DOM相关时(如ajax),并使用 $。fn。当它对使用选择器抓取的元素(如DOM / XML元素)进行操作时。

My rule of thumb I follow is: use $. when it is not DOM related (like ajax), and use $.fn. when it operates on elements grabbed with a selector (like DOM/XML elements).

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

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