简体   繁体   English

存储要与jquery一起使用的数据的最佳方法是什么?

[英]What is the best way to store data to use with jquery?

I am not a heavy user of Javascript/jQuery, but I have start to really get into creating my own UI stuff, such as gallery viewer, alert animations, popup forms etc... 我不是Java / jQuery的重度用户,但是我已经开始真正地创建自己的UI东西,例如画廊查看器,警报动画,弹出表单等。

But what is the best way to store data to pull together when needed? 但是,在需要时存储数据以汇总在一起的最佳方法是什么?

For example: With the gallery viewer, much like Lightbox, I pull in the href of anchors that have the rel=viewer. 例如:使用图库查看器,就像Lightbox一样,我可以拉入具有rel = viewer的锚的href。

<a href="url" rel=viewer" />
<a href="url" rel=viewer" />

I then extended this for admin users to be able to delete these images, but I needed to pass the media id to do this. 然后,我将此扩展为管理员用户可以删除这些图像,但是我需要传递媒体ID来完成此操作。 So I added... 所以我加了...

<a href="url" rel=viewer" viewerid="123" />
<a href="url" rel=viewer" viewerid="456" />

I do not like the idea of creating my own attributes, because I will no doubt forget what I have. 我不喜欢创建自己的属性的想法,因为我无疑会忘记自己拥有的属性。 But is it possible to store a javascript object/array of data within an anchor? 但是是否可以在锚点中存储javascript对象/数据数组? Something like... 就像是...

<a href="url" rel=viewer" data="{'id':'123', 'foo':'bar'}" />

and then... 接着...

var photos = new Array();
$('a[rel=viewer]').each(function(){
    photos.push(  new Array( $(this).attr('data') )  );
});

to give me something like 给我类似的东西

photos[0] = array('id' => 123, 'foo' => 'bar')
photos[1] = array('id' => 456, 'foo' => 'bar')

JQuery 数据功能听起来像您所需要的。

try this one jQuery.data 试试这个jQuery.data

jQuery.data(document.body, 'foo', 52);
jQuery.data(document.body, 'bar', 'test');

as i know data inside tag have to be named? 据我所知标记内的数据必须命名? valid syntactic would be 有效的句法是

<a href="url" rel=viewer" data-array="{'id':'123', 'foo':'bar'}" />

and you can read it later like that: 您以后可以像这样阅读:

$('a').data('array')

For simple purposes, I'd stick with custom data attributes , which are perfectly valid in HTML5. 为简单起见,我会坚持使用自定义数据属性 ,该属性在HTML5中完全有效。

If you need a deeper approach, you'd better decouple data from DOM /jQuery.data, and use a proper model layer in you application [think about Backbone.js ], though it implies a little hard learning curve and may be overkill sometimes. 如果您需要更深层次的方法,则最好将数据与DOM /jQuery.data分离,并在应用程序中使用适当的模型层[想想Backbone.js ],尽管这意味着学习起来有些困难并且有时可能会过大。

The best way I find is using HTML5 data attributes and jQuery. 我发现最好的方法是使用HTML5数据属性和jQuery。

Here is an example using JSON to stringify the object and the turn it back into an object when you need the data. 这是一个使用JSON字符串化对象并将其在需要数据时转换为对象的示例

var obj = 
{
  type: "something",
  id: 3,
  src: "somesrc"    
}

var data = JSON.stringify(obj);
$('a').attr('data-object', data);

var returned = $('a').attr('data-object');
returned = $.parseJSON(returned);
console.log(returned);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM