jQuery库是轻量级的(缩小/压缩后约为25KB),符合CSS3和跨浏览器。 它提供了丰富的API集,包括遍历和操作HTML文档对象模型(DOM),处理事件,并提供了使用异步JavaScript和XML(Ajax)请求API的服务器通信。 此外,它还为网页提供动画和图像效果,以及powerufl插件体系结构。
在本文中,学习如何通过将数据与特定的DOM元素相关联,在jQuery中使用数据存储工具将自定义非可见数据嵌入到网页中。 通过一些深入的示例,学习如何在自己的应用程序中使用它,并了解jQuery如何允许您在基于jQuery的应用程序中使用HTML5 data- *属性。
要继续阅读本文,您将需要:
- 以前接触过HTML
- 对JavaScript基础的理解
- jQuery的基础知识
您可以下载本文中使用的源代码和示例。
将数据附加到DOM元素
有时需要存储与您的网页特定元素关联的隐藏信息或元数据。 提供此信息而不必单独检索它可以简化您的页面和相关代码。 隐藏的信息可以以多种方式使用,例如用于样式设计,在用户选择特定的UI元素时进行计算以及过滤要显示给用户的结果。
通常,在网页中包含隐藏信息需要采取创造性的方法。 例如:
- 在HTML元素属性(例如
id
,class
,rel
和title
存储信息,从而覆盖属性的原始意图。 - 使用包含信息的
<span>
或<div>
块,同时通过样式使这些块对用户不可见(style="display: none;"
)。 - 将JavaScript代码添加到网页以定义映射到HTML ID元素的数据结构。
- 向现有HTML元素添加自己的属性(打破HTML标准本身,并依靠HTML浏览器忽略任何语法错误)。
不同的方法仅受开发人员的创造力限制。
上面的方法不是很好,也不是很好的编码实践。 但是,有个好消息-jQuery具有一种功能,可简化以跨浏览器的方式将数据与DOM元素关联的过程。
jQuery data()
方法
使用jQuery data()
API,您可以存储和检索与特定DOM元素关联的数据。 这是一项非常强大的功能,支持各种数据类型,包括JavaScript对象。 jQuery data()
方法通过将数据隐藏在与特定DOM元素关联的同时将其隐藏,从而将HTML视图与数据真正分离。 这种方法有助于保持HTML本身的干净,并避免Ajax调用来检索所需的其他静态信息。
jQuery JavaScript库定义了两种数据方法,如表1所示。
表1. jQuery数据方法
一般形式 | 描述 | 格式 |
---|---|---|
jQuery.data (或$.data ) | 存储与指定元素关联的任意数据。 | j Query.data(element, key, value) jQuery.data(element, key) jQuery.data(element) |
jQuery.fn.data (or $.fn.data) | 存储与匹配元素关联的任意数据。 | .data(key, value) .data(obj) .data(key) .data() |
使用jQuery.data()
,数据与特定的DOM元素关联。 这种形式不像jQuery.fn.data()
那样实用,因为它要求您选择并跟踪感兴趣的元素。 尽管这种形式的data()
比其他形式要快得多,但它是供jQuery框架供低层使用的。
使用jQuery.fn.data()
,数据与匹配指定jQuery选择标准的DOM元素相关联。 这是一种更实用的方法,因为jQuery根据传递的选择条件为您执行元素的选择。 $.fn.data
执行元素选择器,并且比$.data
慢
从jQuery 1.4.3开始, $fn.data()
将从HTML DOM返回HTML5数据属性。 HTML5数据存储和jQuery对此有更多详细信息。
本文的其余部分主要关注jQuery.fn.data()
。
jQuery中基于DOM的数据存储和检索
首先,一些基本知识。 当浏览器加载网页(或XML文档)时,将对其进行解析并创建其DOM表示形式。 清单1显示了一个简单HTML文件的示例。
清单1.简单HTML文件
<table>
<tbody>
<tr>
<td>Shady Grove</td>
<td>Aeolian</td>
</tr>
<tr>
<td>Over the River, Charlie</td>
<td>Dorian</td>
</tr>
</tbody>
</table>
图1显示了从原始W3C规范文档重新创建的关联DOM(请参阅参考资料中的链接)。
图1.清单1中HTML的DOM图形表示
![清单1中HTML的DOM图形表示。](https://i-blog.csdnimg.cn/blog_migrate/a3d5a54d1f68adedbd2148760b1aa55c.png)
使用DOM,可以以编程方式访问,添加,删除或更改HTML或XML文档中找到的所有内容(元素和内容)。
使用jQuery,您可以将JavaScript数据类型(字符串,数字,对象,数组,事件和函数)与特定的DOM元素相关联。 数据存储在内部索引的jQuery缓存JavaScript对象中。 命名数据和DOM元素之间的关联使jQuery中基于DOM的数据存储和检索成为可能。 清单2显示了缓存的定义和jQuery.data()
方法。
清单2. jQuery.cache和低级jQuery.data()
方法的定义
(function( jQuery ) {
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
expando: "jQuery" + jQuery.now(),
:
:
data: function( elem, name, data ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
elem = elem == window ?
windowData :
elem;
var isNode = elem.nodeType,
id = isNode ? elem[ jQuery.expando ] : null,
cache = jQuery.cache, thisCache;
if ( isNode && !id && typeof name === "string"
&& data === undefined ) {
return;
}
// Get the data from the object directly
if ( !isNode ) {
cache = elem;
// Compute a unique ID for the element
} else if ( !id ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
}
// Avoid generating a new cache unless none exists and we
// want to manipulate it.
if ( typeof name === "object" ) {
if ( isNode ) {
cache[ id ] = jQuery.extend(cache[ id ], name);
} else {
jQuery.extend( cache, name );
}
} else if ( isNode && !cache[ id ] ) {
cache[ id ] = {};
}
thisCache = isNode ? cache[ id ] : cache;
// Prevent overriding the named cache with undefined values
if ( data !== undefined ) {
thisCache[ name ] = data;
}
return typeof name === "string" ? thisCache[ name ] : thisCache;
},
:
:
jQuery.fn.data()
方法的定义与此类似。 作为一个单独的练习中,您可以探索它的定义,使用data.js在Github上寻求帮助(请参阅相关信息中的链接)。
在以下各节中,学习如何存储和检索与给定DOM元素相关联的索引jQuery数据缓存中存储的数据。
存储和检索数据
如前所述,使用jQuery可以执行基于DOM的数据存储和任何JavaScript数据类型的检索,包括字符串,数字,对象,数组,事件和函数。 数据存储在内部索引的jQuery缓存JavaScript对象中。
为了显示如何使用jQuery数据方法存储和检索数据,下面的示例涉及一个Web页面,该页面使用基于CSS的表和过滤器函数根据与特定行DOM元素关联的数据过滤行。 图2显示了一个示例。
图2.基于DOM的数据存储和检索,示例网页
![该表的左侧有一个过滤器部分,并有四列不同的过滤条件。](https://i-blog.csdnimg.cn/blog_migrate/19feccf45059da667cfe81e248cb9e98.png)
样本中的内容是一个表,该表显示了餐厅名称,提供的食物类型,位置以及餐厅的等级。 该网页的主体由几个<div>
部分组成,这些部分定义了侧边栏以及表或网格本身,如清单3所示。
清单3. HTML内容
<body>
<div id="sidebar">
Filter by type, location or rating:
<input type="text" />
<button id="filter">Filter</button>
<button id="clear">Clear</button>
<p>
To keep the sample code simple, the search terms are "ORed". Example
"seafood 2 stars downtown" which returns all rows that match seafood OR 2+ stars
OR in downtown.
</p>
</div>
<div id="rows">
<p>
This sample web page shows how to use the <code>jQuery.data()</code>
method. It uses a CSS-based table and a filter function that filters rows based on the
data associated with the particular row DOM-element.
</p>
<div class="row" id="row1">
<div class="cell"><b>Restaurant</b></div>
<div class="cell"><b>Type of Food</b></div>
<div class="cell"><b>Location</b></div>
<div class="cell"><b>Rating</b></div>
</div>
<div class="row" id="row2">
<div class="cell">Manuel's</div>
<div class="cell">Mexican</div>
<div class="cell">Arboretum Area, Downtown</div>
<div class="cell">3 Stars</div>
</div>
<div class="row" id="row3">
<div class="cell">NoRTH</div>
<div class="cell">Italian</div>
<div class="cell">North Austin</div>
<div class="cell">4 Stars</div>
</div>
<div class="row" id="row4">
<div class="cell">Perlas Seafood</div>
<div class="cell">Seafood</div>
<div class="cell">Downtown</div>
<div class="cell">5 Stars</div>
</div>
<div class="row" id="row5">
<div class="cell">Rudys</div>
<div class="cell">BBQ</div>
<div class="cell">North Austin, Downtown, South Austin, Round Rock,
Dallas</div>
<div class="cell">3 Stars</div>
</div>
<div class="row" id="row6">
<div class="cell">Chuys</div>
<div class="cell">Tex Mex</div>
<div class="cell">North Austin, Downtown, South Austin</div>
<div class="cell">2 Star</div>
</div>
<div class="row" id="row7" data-id="7" data-type="Sushi" data-stars="3"
data-area="downtown">
<div class="cell">Midoro</div>
<div class="cell">Sushi</div>
<div class="cell">Downtown</div>
<div class="cell">4 Star</div>
</div>
</div>
</body>
每行都是一个类行,并且具有唯一的ID,该ID用于标识DOM元素并将数据与其关联。 清单4显示了一个示例。
清单4. CSS中的表行和唯一ID
<div class="row" id="row6">
<div class="cell">Chuys</div>
<div class="cell">Tex Mex</div>
<div class="cell">North Austin, Downtown, South Austin</div>
<div class="cell">2 Star</div>
</div>
清单4是示例网页的静态部分。 网页的其余部分是JavaScript,它使用jQuery来存储与特定DOM元素关联的数据,检索数据并根据过滤条件动态过滤信息。
使用JavaScript和jQuery
在JavaScript中,第一个任务是将click处理程序添加到ready()
事件处理程序中,如清单5所示。
清单5. ready()
事件处理程序
<script type="text/javascript">
/* Ready */
$(document).ready(function() {
$('#filter').click(function () {
filterRows($('input').val());
});
$('#clear').click(function () {
$('input').val('')
clearRows($('input').val());
});
});
:
:
该代码为过滤器和清除按钮添加了单击处理程序。 筛选按钮触发表视图内容筛选,而清除按钮将表重置回其原始视图状态。
遵循图2所示示例的下一步是让jQuery代码将隐藏的元数据与特定的DOM元素相关联。 为此,您需要关联一个保存元数据JavaScript对象。 在此示例中,每个表行的ID,类型,星号和区域的属性。 清单6显示了一个示例,该示例如何使用jQuery选择器选择特定的DOM元素,以及如何为所选元素调用.data()
以将JavaScript对象添加到DOM元素。 与JavaScript对象一样,其他成员数据类型可以是整数,字符串和更复杂的类型,例如数组,函数和其他对象。
清单6.将数据关联到特定的DOM元素(jQuery)
:
:
/* Associate data to specific DOM-elements */
$('#row1').data({ id:1, type:'rowheader'});
$('#row2').data({ id:2, type:'mexican', stars:3, area:'north'});
$('#row3').data({ id:3, type:'italian', stars:4, area:'north'});
$('#row4').data({ id:4, type:'seafood', stars:5, area:'downtown'});
$('#row5').data({ id:5, type:'bbq', stars:3, area:'west'});
$('#row6').data({ id:6, type:'tex mex', stars:2, area:'south'});
:
:
清单7显示了清单5中描述的添加到$(document).ready()
函数中的单击处理程序的实现。函数clearRows()
用于将表视图重置为其原始状态,而filterRows()
用于过滤表视图。基于筛选条件的表格视图与存储的DOM数据进行比较。
清单7. Click处理程序
:
:
/* Clear Rows */
function clearRows(filterString) {
// For each row, that is, div in #rows of class .row
$.each($('#rows .row'), function(i, row) {
$(row).show();
});
}
/* Filter Rows */
function filterRows(filterString) {
// For each row, that is, div in #rows of class .row
$.each($('#rows .row'), function(i, row) {
var $row = $(row); // Get the row div element
var rowData = $row.data(); // Get the data associated with the row
div element
var id = rowData.id; // Get the row id
var type = rowData.type;
if (filterString.length == 0) {
$row.show();
} else {
if (type.toLowerCase().search("rowheader") != -1) {
$row.show();
} else {
if (filterByType(filterString, rowData.type) ||
filterByRating(filterString, rowData.stars) ||
filterByLocation(filterString, rowData.area)) {
$row.show();
} else {
$row.hide();
}
}
}
});
}
:
:
让我们仔细看看代码如何为每个表行执行jQuery选择器: $.each($('#rows .row')
和function(i, row)
。对于每个选定的行,提取row元素及其相关数据,如清单8所示。
清单8.检索DOM元素数据
var $row = $(row); // Get the row div element
var rowData = $row.data(); // Get the data associated with the row div element
其余功能根据类型,等级(或星号)和区域/位置执行实际过滤。 清单9显示了一个示例。
清单9.根据DOM元素数据过滤内容
:
:
/* Filter Rows by Type */
function filterByType(filterString, type) {
var p1 = RegExp(type);
if (p1.test(filterString)) {
return true;
} else {
return false;
}
}
/* Filter Rows by Rating */
function filterByRating(filterString, stars) {
if (filterString.toLowerCase().search('star') != -1) {
var value = filterString.replace(/[^0-9]/g,'');
if (stars >= value) {
return true;
} else {
return false;
}
}
}
/* Filter Rows by Location */
function filterByLocation(filterString, area) {
var p1 = RegExp(area);
if (p1.test(filterString)) {
return true;
} else {
return false;
}
}
</script>
您可以通过添加其他过滤逻辑和功能来更改或改进清单9中的代码。
您可以下载 dom-based-data-sample.html文件,以获取上述所有HTML内容,关联JavaScript和jQuery代码供您自己使用。
HTML5数据存储和jQuery
HTML5引入了新的自定义数据属性,用于在网页中嵌入自定义的非可见数据。 正如W3C所定义的那样,“这些新的自定义数据属性旨在存储页面或应用程序专用的自定义数据,对于这些页面或应用程序,没有更多合适的属性或元素。”
从jQuery的角度来看,新HTML5自定义数据属性针对的是jQuery data()
方法解决的同一问题。 HTML5数据属性仅限于字符串数据。 使用jQuery data()
您可以存储任何类型JavaScript数据类型,从整数和字符串到数组,函数和其他对象。
从jQuery 1.4.3开始, .data()
自动提取,存储(在缓存中)并从HTML DOM返回HTML5数据属性。
HTML5数据属性定义为data-* attributes
,其中data-
是data-* attributes
的必需前缀名称,而*
可以是W3C定义的任何字符序列。 定制数据属性是没有名称空间的属性,该名称空间的名称以字符串“ data-”开头,连字符后至少包含一个字符,与XML兼容,并且不包含U + 0041至U + 005A范围内的字符(拉丁大写字母A到拉丁大写字母Z)。
清单10中HTML代码片段包含一个行定义,该行定义使用.data()
APU添加了上面添加的相同元数据,但是这次使用HTML5自定义属性。
清单10.使用HTML5的基于DOM的数据
<div class="row" id="row7"
data-id="7"
data-type="Sushi"
data-stars="3"
data-area="downtown">
<div class="cell">Midoro</div>
<div class="cell">Sushi</div>
<div class="cell">Downtown</div>
<div class="cell">4 Star</div>
</div>
该解决方案的优点在于您不必更改代码即可支持HTML5。 jQuery data()
自动检测到客户数据属性,将其解析,将其加载到缓存中,并在请求时返回它们。
结论
在本文中,您学习了jQuery data()
方法,重点介绍了jQuery.fn.data()
。 这些jQuery数据存储功能使您可以通过将数据与特定的DOM元素相关联,将自定义的非可见数据嵌入到网页中,从而提供基于DOM的数据存储和检索。 现在,您可以以干净的方式存储任何类型JavaScript数据。
翻译自: https://www.ibm.com/developerworks/web/library/wa-domjquery/index.html