问题描述:

I want to create a sub-namespace in jQuery. I've tried this:

$.fn.tx = function() {

console.log(this);

return this;

};

$.fn.tx.lib = function() {

console.log(this);

return this;

};

If I write,

$('selector').tx();

Firebug will show my selected DOM. But if

$('selector').tx.lib();

It shows an empty function.

I don't know why this happened. Does anyone have any ideas? Thanks in advance.

网友答案:

This really isn't the correct way to namespace in jQuery. I was confused about this at first also when I went to write my first plugin. There's some good documentation at the jQuery plugin authoring page.

In a nutshell, you want to define your namespace as you've done in your first sample:

$.fn.tx = function(args) {
  console.log(this);
  return this;
};

And then inside there you can define functions that you'd like 'namespaced', and call them as on the jQuery docs. Hope this helps!

相关阅读:
Top