开发者

Using $.data() in jQuery to store flag on element

I am authoring a simple jQuery plugin that turns an input tag into a time-formatted element (on blur it开发者_高级运维 will change 245p into 2:45 pm).

Since I do not want to apply the time format events to the same element twice, I need a way to detect that the specific element in the list provided has not already had the format applied.

This is the relevant part of the code:

var methods = {
    init : function(sel) {
        var $this = $(sel);
        return $this.each(function(){
            var data = $(this).data('time_formatted');
            if (data) {
                return;
            } else {
                $(this).data('time_formatted', true);

I have heard that using $(sel).data() in a plugin is not a good idea; instead, use $.data(). I don't know why, that's just what I've heard; honestly, I don't know what the difference is.

So my question is, is this the way to accomplish checking if a specific element has had the time formatter applied to it in a plugin?

If you care to see the plugin in it's current development state, see http://jsfiddle.net/userdude/xhXCR/.

Thanks!

Jared


Where have you heard that using .data() is not good? jQuery's plugin autoring page says:

Often times in plugin development, you may need to maintain state or check if your plugin has already been initialized on a given element. Using jQuery's data method is a great way to keep track of variables on a per element basis. However, rather than keeping track of a bunch of separate data calls with different names, it's best to use a single object literal to house all of your variables, and access that object by a single data namespace.

So it should be perfectly fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜