我应该将html元素的jQuery数据存储在哪里
Where should I store jQuery data for html elements?
为了更好地学习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() });
现在width
和height
是存储在.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
对象的数据。这是可行的,但您可以通过这样调用它来获得保存的width
和height
:
$(this).data("width");
$(this).data("height");
- 如何有效地将游戏数据存储在URL查询字符串中
- 将数据存储在javascript数组中以供进一步使用
- 将数据存储到元素中
- 如何将变量数据存储在其他变量中并对其进行解析
- 将新类实例中的数据存储在数组中
- 如何在Java Script中比较二维数组和一维数组,并将常见数据存储在另一个数组中
- 组合框是否需要数据存储
- 将动态feild数据存储到jquery-mobile和php-mysql中的数据库中
- 将数据存储在请求与请求中
- 将json数据存储在sqlite(phonegap应用程序)中
- 如何给$('inputs')每个函数,以将数据存储为 asp.net 中的键值对
- 使用 Ajax 将 PHP 嵌入到 JavaScript 中,以便将 MySQL 数据存储在 JavaScript 对象
- 无法将数据存储到 mongoDB
- Ext JS - 将面板绑定到数据存储的最佳方法
- 如何将数据存储值传递给javascript?我需要从gae数据存储中获取数据,并需要传递javascript
- 在数组数组中查找表数据存储
- 客户端数据存储
- 如何使用javascript将数据存储到mysql数据库中
- ServiceWorker数据存储在哪里
- Javascript Security:将敏感数据存储在比cookie更安全的自调用函数中