Test

Page 152

CSS div { color:blue; } span { color:red; }

HTML <div> The values stored were <span></span> and <span></span> </div>

data Returns value at named data store for the first element in the jQuery collection, as set by data(name, value). data():Object

Added in version 1.4

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set: alert($('body').data('foo')); alert($('body').data());

The above lines alert the data values that were set on the body element. If no data at all was set on that element, undefined is returned. alert( $("body").data("foo")); //undefined $("body").data("bar", "foobar"); alert( $("body").data("foobar")); //foobar

HTML 5 data- Attributes As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification. For example, given the following HTML: <div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

All of the following jQuery code will work. $("div").data("role") === "page"; $("div").data("lastValue") === 43; $("div").data("hidden") === true; $("div").data("options").name === "John";

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery). Calling .data() with no parameters retrieves all of the values as a JavaScript object. This object can be safely cached in a variable as long as a new object is not set with .data(obj). Using the object directly to get or set values is faster than making individual calls to .data() to get or set each value: var mydata = $("#mydiv").data(); if ( mydata.count < 9 ) { mydata.count = 43; mydata.status = "embiggened"; }

Example 1:

Get the data named "blah" stored at for an element.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.