Create an element once in a jquery plugin
I've written quite a few jQuery plugins in the past and this problem has come up a couple times now. Usually I just create a global variable outside the closure and call it a day. This time I'm trying to figure out what the proper way of doing it is.
So here's the deal. I have my base plugin setup like this:
(function($) {
$.fn.nameOfPlugin = function(options) {
var defaults = {
foo: 'foo'
}
var opts = $.extend(defaults, options);
re开发者_运维技巧turn this.each(function(){
//if first time through call create
});
};
function create() {
//create stuff here only once
$('body').append("<div id='plugin_overlay'></div>");
};
})(jQuery);
and obviously I would initate it like this:
$('.class').nameOfPlugin({foo:'bar'});
Since I am using a class as a selector return this.each could run anywhere from 1 to 50 times. What is the best way to run the create method only once per selector?
I realize that in this situation I can simply check:
$('#plugin_overlay').length > 0
but I will be adding a timestamp at the end of the id so it is unique based on the selector.
I do have a couple more ideas onto what I can do, im just wondering what is the best way to do this.
I may be completely misunderstanding the question here, but if you only want to call the method once per selector, why not just call it prior to the each?
create();
return this.each(function(){
...
});
Alternatively, you can use the index parameter which is passed to the each function:
return this.each(function(i){
if(i==0) create();
...
});
精彩评论