I got this amazing tip from an article named “5 tips for better jQuery code”.
This is a great way to associate any amount of data with any element on the page, here is a small example:
<html>
<head>
<title>jQuery Data() method</title>
<script src="scripts/jquery/jquery-1.2.6.min.js" type="text/javascript"></script>
    <script type="text/javascript">
            $(document).ready(function() {
                //create meaningless list
    for(var i=0;i < 10;i++)
            {
    $("#list").append("<li>" + i + "</li>");
}
            var prevSum = 0;
                //will show the pwr of index and sum with all previous items
    $("#list li").each(function(indx, obj)
            {
    prevSum = prevSum + indx;
                //attach data to each list item
    $(this).data("Data", {pwr: indx*indx, sum: prevSum });
                //Show it
    $(this).html($(this).html() + ": pwr=" + $(this).data("Data").pwr + ",sum=" + $(this).data("Data").sum);
});
});
</script>
</head>
<body>
    <ul id="list">
    <!--the items will be added here -->
</ul>
</body>
</html>
Nice!
The interesting part is that the data is not shown in the source code…
it's not in the source because it was added dynamically, therefore hosted in the DOM...
ReplyDelete