我应该将html元素的jQuery数据存储在哪里

Where should I store jQuery data for html elements?

本文关键字:数据 存储 在哪里 jQuery html 元素 我应该      更新时间:2023-09-26

为了更好地学习jquery,我决定写一个插件,像google+一样创建画廊拼贴效果。下面是一个例子。

我想在调整包含图像的html元素的大小时再次触发它。我遇到的部分问题是,我需要存储原始图像大小,以便重新计算图像大小以使其适合。

我不知道在哪里存储,也不知道如何检索那些原始图像大小。上面链接了完整的插件,但我会在这里做一个总结。

;(function( $ ) {
    $.fn.collagePlus = function( options ) {
        var settings = $.extend( 
            //... 
            'images'          : $('img', $(this))
            //... 
        );
        return this.each(function() {
            settings.images.each(function(index){
                //... 
                /*
                * get the current image size
                */
                var w = (typeof $(this).data().width != 'undefined') ? $(this).data().width : $(this).width();
                var h = (typeof $(this).data().height != 'undefined') ? $(this).data().height : $(this).height();
                /*
                * store the original size for resize events
                */
                $(this).attr( "data-width" , w  );
                $(this).attr( "data-height" , h  ); 
                //... Do some other stuff
                }
            );
        });
    }
})( jQuery );

您使用.data()错误。将1个参数传递给.data函数时,它将返回给定键的值。当您传递2个参数时,.data将设置该键的值。

此区块:

//get the current image size
var w = (typeof $(this).data().width != 'undefined') ? $(this).data().width : $(this).width();
var h = (typeof $(this).data().height != 'undefined') ? $(this).data().height : $(this).height();

应为:

var $this = $(this); //caching your selector
if (!$this.data('width')) //if this element doesn't have a width stored
    $this.data('width', $this.width()); //stores currently computed width
if (!$this.data('height')) //repeat
    $this.data('height', $this.height());

当然,为了稍后检索数据:

alert($this.data('width')) //alerts currently stored width

Fiddle演示

您也可以将对象存储在.data中,传递属性映射:

if (!$(this).data('size'))
    $(this).data('size', { width: $(this).width(), height: $(this).height() });

现在widthheight是存储在.data('size')中的对象的属性,可以使用检索

alert($(this).data('size').width);

Fiddle

为了简单起见,我主要选择第一个选项。然而,第二个看起来更整洁。选择您认为可读性和可维护性更强的。

在服务器端,您可以将HTML元素的数据存储在data-*属性中,并通过jQuery的.data()函数获取数据(自jQuery 1.4.3以来,它也改变了该函数的一般行为,如文档中所述)。您正在插件中设置属性,但此时,您可以将原始宽度和高度存储在data对象中,如下所示:

$(this).data( "data-width", w );
$(this).data( "data-height", h );

无论数据是作为data-属性存储在HTML中,还是包含在附加到元素的jQuery的data对象中,使用.data()函数都会返回数据。您已经在使用不带任何参数的.data()函数,该函数返回匹配元素的完整data对象,还包含来自HTML属性和jQuery的data对象的数据。这是可行的,但您可以通过这样调用它来获得保存的widthheight

$(this).data("width");
$(this).data("height");