HTML and CSS Reference
In-Depth Information
Example: The jQuery data() method
The jQuery library has provided support for accessing and manipulating custom data
since version 1.4.3. This support was updated in jQuery 1.6 to conform to changes in
the HTML5 specification; use this version of jQuery if possible (see http://www.web
monkey.com/2011/05/jquery-update-improves-html5-data-tools/ ).
Using the jQuery data() method is straightforward. Let's return to an earlier example
to see how it works:
<ul>
<li data-year="1996" data-color="white" data-engine="VR6">Cabrio</li>
</ul>
<script>
alert($("li").data("year")); // alerts "1996"
alert($("li").data("engine")); // alerts "VR6"
// let's repaint the car again
$("li").data("color", "yellow");
// and add the rating data
$("li").data("rating", "awesome");
</script>
The jQuery data() method successfully reads the data-year and data-engine attributes
defined in the markup, but if you access data-color via the dataset API or examine the
DOM object, you neither see its value turn yellow nor find a data-rating attribute, as
you did in Recipe 6.5 :
<script>
alert($("li").data("color")); // alerts "yellow"
alert(document.getElementsByTagName("li")[0].dataset.color); // alerts "white"
</script>
While jQuery reads in the data from the custom data attributes, it does not write this
data back to the DOM; instead, it stores the data in a JavaScript object. This speeds up
applications where a lot of data access or manipulation is performed. However, if you
forget this difference and try to also use the dataset API in your application, you will
encounter some unexpected results.
See Also
A small sampling of applications utilizing microdata:
• PaintbrushJS by Dave Shea: http://mezzoblue.github.com/PaintbrushJS/demo/inde7
.html
• Dynamic Google Analytics Tagging by Jason Karns: http://jasonkarns.com/blog/
2010/03/10/google-analytics-tagging/
• SXSW 2010 Parties site by Christopher Schmitt, Kyle Simpson, Stephanie Sullivan,
and Zoe Gillenwater: http://www.sxswcss3.com
 
Search WWH ::




Custom Search