0

Let's say I have an array of Customer structures and I need to generate HTML from it.

Currently I do something like this:

jQuery.each(customers, function(index, item) {
     html =+ "<tr custID='" + item.ID + "'><td>" + item.Name + "</td><td>" + item.City + "</td></tr>";  
});

The issue here is that I manually add the custID attribute. I believe the cool way to do this would be using jQuery's Data function.

But how would I use it in this scenario?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
David
  • 1,051
  • 5
  • 14
  • 28

3 Answers3

2

The elegant way is not to append those html tags as if they are text, but create element using

document.createElement("tr");

you can modify its attributes and then append it to the html file.

Read more here:

jQuery document.createElement equivalent?

Community
  • 1
  • 1
Jonathan Chow
  • 703
  • 7
  • 29
1

Just prefix the attribute with data-:

jQuery.each(customers, function(index, item) {
  html += "<tr data-custID='" + item.ID + "'><td>" + item.Name + "</td><td>" + item.City + "</td></tr>";  
});

Now you can access the data using the methods in jQuery.

(I changed the non-existing =+ operator to +=. Guess it was just a typo in the question.)

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You can use data grid i think it is much cooler than manually creating tables. But in your case you have to use append() function.

Here is good examples: http://jquery-howto.blogspot.com/2009/02/add-table-row-using-jquery-and.html http://api.jquery.com/append/

Johndave Decano
  • 2,101
  • 2
  • 16
  • 16