开发者

persistant functions on a jquery object

I know you can store stuff in a jQuery object using .data(), and whenever that element is found, regardless of the selector used, your data will be there.

You can also use .sub() to create branches of jQuery with your own functions and use that sub to select elements.

But is there a way to simply say $("#something").foo = function() { ... };, and then later go $("#something").foo()开发者_如何学运维;?

It doesn't seem like it would be that hard a plugin to write. And to me it seems that would be an awesome tool to have. Is there some reason I can't find it?


jQuery objects aren't persistent which means a new jQuery object will be created each time you say $("#something"). That means, it actually goes and searched the Dom tree each time for a element where id=something.

If you want to add a function to that, you can just store the jQuery object in a variable and later on, reference that variable like this:

var something = $("#something");
something.foo = function() { ... }
// Later on
something.foo();

You can also really easily extend jQuery's behavior with your own plugin by saying,

jQuery.fn.foo = function() {

  // Do your awesome plugin stuff here

};

Then you can directly make a call like $("#something").foo();


That's not possible, because everytime you use the $ function, it creates a new jquery object, so you'd lose the added properties or methods.

$("#something").foo = function() { ... }
$("#something").foo(); //Error. foo is not a function

However, you could add this method directly to the dom element (but it's not recommended), like this:

$("#something")[0].foo = function() { ... };
$("#something")[0].foo(); //foo() gets executed!!

but you would have to be carefull, you could overwrite an existent dom method or property. For example, if you name your method 'innerHTML' you would overwrite that property. That's why it's not recommended.

Hope this helps. Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜