我过去也以几种不同的方式这样做过。
$('selector').data 的想法可能是最有用的技术之一。我喜欢这种存储数据的方式,因为我可以以一种合乎逻辑、直观和有序的方式存储数据。
假设您有一个在页面加载时检索 3 篇文章的 ajax 调用。文章可能包含与标题、日期/时间、来源等相关的数据。让我们进一步假设您要显示标题,当点击标题时,您希望显示完整的文章及其详细信息。
为了说明这个概念,假设我们检索的 json 看起来像这样:
{
articles: [
{
headline: 'headline 1 text',
article: 'article 1 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
},
{
headline: 'headline 2 text',
article: 'article 2 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
},
{
headline: 'headline 3 text',
article: 'article 3 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
}
]
}
来自这样的 ajax 调用。 . .
$.ajax({
url: "news/getArticles",
data: { count: 3, filter: "popular" },
success: function(data){
// check for successful data call
if(data.success) {
// iterate the retrieved data
for(var i = 0; i < data.articles.length; i++) {
var article = data.articles[i];
// create the headline link with the text on the headline
var $headline = $('<a class="headline">' + article.headline + '</a>');
// assign the data for this article's headline to the `data` property
// of the new headline link
$headline.data.article = article;
// add a click event to the headline link
$headline.click(function() {
var article = $(this).data.article;
// do something with this article data
});
// add the headline to the page
$('#headlines').append($headline);
}
} else {
console.error('getHeadlines failed: ', data);
}
}
});
我们可以将相关数据存储到 dom 元素中,并在以后需要时访问/操作/删除该数据。这减少了可能的额外数据调用并有效地将数据缓存到特定的 dom 元素。
标题链接添加到文档后的任何时候,都可以通过 jquery 选择器访问数据。要访问第一个标题的文章数据:
$('#headlines .headline:first()').data.article.headline
$('#headlines .headline:first()').data.article.article
$('#headlines .headline:first()').data.article.source
$('#headlines .headline:first()').data.article.date
通过选择器和 jquery 对象访问您的数据非常简洁。