jquery data()

本文深入探讨了jQuery中.data()方法的使用,包括如何存储和检索与匹配元素关联的任意数据,以及如何通过HTML5的数据-*属性进行操作。通过实例展示了如何设置和获取数据,同时解释了jQuery如何解析camel-cased字符串并将其转换为dashed string。

data()

.data( key, value )

  Description: Store arbitrary data associated with the matched elements.

  • .data( key, value )
  • .data( obj )

.data( key )

  Description: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

  • .data( key )
  • .data()

Example1

$( "body" ).data( "foo", 52 ); 
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data();
// { foo: 52, bar: { myType: "test", count: 40 }, baz: [ 1, 2, 3 ] }

Example2

HTML5 data-* Attributes
<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

Additional:

jQuery searches among the attributes of the element, converting a camel-cased string into a dashed string and then prepending data- to the result. So, the string lastValue is converted to data-last-value.

 

转载于:https://www.cnblogs.com/hzj680539/p/5031327.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值