Question

For the past few weeks, i have been using jQote – client-side templating plugin to generate html fragments in runtime.

For months i have been using the dom attributes like, id, class, alt to store critical data.

Now, I came to know about .data() method in jquery to store and retrieve data.

All over my project i am generating html fragments dynamically using templates.

Now i need to know how can i use .data() in these templates dynamically and store critical data within any dynamically created element.

The template js code is like this,

var template = templateCache.idOfTheTemplate; // say its a <li>
for(var i = 0; i < length; i ++){
$("#ulID").jqotepre(template, data);
}

Template:

<script id="idOfTheTemplate" type="text/template">
<li id="<%=this.id%>">//here i want to use .data() and store the id with different key
<a id="<%=this.id%>" href="#"><%=this.linkName%></a>
</li>
</script>

Solution:

 $("#ulID").jqotepre(template, data);

After this line has been executed, that element was available in the DOM.

So, you can just do this,

$("#ulID").jqotepre(template, data);
$('#' + data.id).data('liInfo', data);//data.id is the ID of the li element in the DOM
Was it helpful?

Solution

The .data() function in JQuery works on html5 data elements.

Meaning

<li id="myId" data-food="value" > 

Is the same as

$("#myId").data('food', 'value');

You can read more on html5 data elements at http://html5doctor.com/html5-custom-data-attributes/

And more on JQuerys data function at http://api.jquery.com/jQuery.data/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top