How to include array content in HTML?
I have this code
var users = result.users; // array
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
he开发者_Go百科ight: 140,
modal: true,
open: function() {
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
},
buttons: {
"Okay": function() {
$(this).dialog("close");
},
Cancel: function() {
is_okay = 0;
$(this).dialog("close");
}
}
});
where the array contain data in the form of
{"ss":"Sandra Schlichting","fn":"Full name"}
What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)
<table>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
<tr> <td>ss </td> <td>Sandra Schlichting</td> </tr>
<tr> <td>fn </td> <td>Full name </td> </tr>
</table>
and have that replaced with <b>New text goes here</b>
in
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
From what I can tell $.each()
should be used for this.
But still I can't quite figure out how to get started.
Can anyone help me out?
You can use a JS for-in
to loop through it.
<table id='nameTable'>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
</table>
var names = {
"ss": "Sandra Schlichting",
"fn": "Full name"
};
var $table = $('#nameTable');
var row = '';
for (name in names) {
row += '<tr><td>' + name + '</td><td>' + names[name] + '</td></tr>';
}
$table.append(row)
Here's a fiddle : http://jsfiddle.net/exP2b/4/
function makeTable(users) {
var result = '<table><tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
alert(makeTable({"ss":"Sandra Schlichting","fn":"Full name"}));
- Working here
$.each
documentation
精彩评论