且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用命名空间创建jQuery元素方法

更新时间:2022-12-01 11:17:48

如果不需要与IE8兼容,则可以使用

If you don't need to be compatible with IE8, you may use Object.defineProperty.

工作示例:

 Object.defineProperty($.fn, 'namespace', {
  get: function(){
    var t = this;
    return {
      lowercasehtml: function(){
         return t.html(function(_,h){ return h.toLowerCase() }); 
      }
    }
  }
});

$('#a').namespace.lowercasehtml(); // changes the html of #a to lowercase (yes, it's stupid, I know)

演示

Demonstration

但是我不相信这样的命名空间是个好主意.我会简单地定义

But I'm not convinced it's a good idea to namespace like this. I would have simply defined

$.fn.namespace_lowercasehtml = function() ...

这就是我个人对jQuery的应用程序特定扩展所做的.

That's what I personally do for my application specific extensions to jQuery.