jQuery data()函数做什么 [英] what does jQuery data() function do
问题描述
我还没有找到jquery函数data()
的用途.
谁能给我一些如何使用它的例子?
I have not found what is the use of jquery function data()
.
Can anyone give me some example of how it can be used?
推荐答案
它对于将各种对象,字符串,数组等与DOM元素相关联非常有用.假设有一个有趣的用法:
Its really useful for associating various objects, strings, arrays, etc with a DOM element. Here is a fun hypothetical use:
$(document).ready(function(){
$("a").each(function(index, el){
if(index % 2 == 0)
$(this).data('coolColor', 'Orange'); // Set the data
else
$(this).data('coolColor', 'Purple'); // Set the data
}).click(function(e){
alert($(this).data('coolColor')); // Retrieve the data
e.preventDefault();
});
});
这将选择每个a
标记,并将Orange
设置为奇数,将Purple
设置为偶数.如果您确实想这样做,这不是编写此代码的最佳方法,但是它确实说明了如何使用.data()
函数.
This would select every a
tag, and set Orange
if its odd, or Purple
if its even. This is not the most optimal way to write this code if this is what you really wanted to do, but it does illustrate how to use the .data()
function.
您还可以使用它来存储对象:
You can also use it to store objects:
$("#header").data('headerSettings',{
color: "red",
cost: "$25.00",
time: 1000
});
现在您可以在页面上的其他任何地方访问该数据:
Now you could access that data anywhere else on the page:
$("#header").data('headerSettings').color;
这篇关于jQuery data()函数做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!