formated output of JS contents into a HTML table
i have a javascript file with the following content and would like to generate a dynamic html table with it's content
(function($) { My.Shortcuts = { a: 'Name', b: 'Elvis', c: 'Fun' }; My.Plugins.extend({ Name: { url: 'http://www.name.com' example: 'some example text here' }, Elvis: { url: 'http://www.elvis.com' }, Fun: { url: 'http://anothersite.com' } }); })(jQuery);
result should be a html table or div list like:
a | Name | http://www.name.com (some example text here) b | Elvis | http://www.elvis.com c | Fun | http://anoth开发者_JAVA技巧ersite.com
unfortunately i have no clue how to do this?
var table_html = '<table><tbody>';
for(var el in My.Shortcuts) {
var coresp_elem = My.Plugins[My.Shortcuts[el]];
table_html += '<tr>';
table_html += '<td>' + el + '</td>';
table_html += '<td>' + My.Shortcuts[el] + '</td>';
// replace line below with for..in loop iterating over coresp_elem
// properties if you are dealing with multiple properties (more info below)
table_html += '<td>' + coresp_elem.url + '</td>';
table_html += '</tr>';
}
table_html += '</tbody></table>';
alert(table_html);
Should work assuming you are going to use it inside the closure with scope access to the My.Shortcuts and My.Plugins objects.
This will produce html string which you can then put somewhere on your page with:
$('.somewhere_on_a_page').html(table_html);
If you wanted to list all properties of the My.Plugins objects (like url, example, name, title, author or whatever you could have there) - you could add another for..in loop inside this one that would iterate over these properties to list all of them - you should be able to handle it from here I believe - if needed help let me know!
Tom
var table = $('<table>');
for (var key in My.Shortcuts) {
if (My.Shortcuts.hasOwnProperty(key)) {
var row = $('<tr>');
var shortcut = My.Shortcuts[key];
$('<td>').text(key).appendTo(row);
$('<td>').text(shortcut).appendTo(row);
if (My.Plugins.hasOwnProperty(shortcut) && typeof My.Plugins[shortcut] === 'object') {
$('<td>').text(
(My.Plugins[shortcut].hasOwnProperty('url') ?
My.Plugins[shortcut].url : '') +
(My.Plugins[shortcut].hasOwnProperty('example') ?
'(' + My.Plugins[shortcut].example + ')' : '')
).appendTo(row);
}
row.appendTo(table);
}
}
This creates a table element dynamically which will be stored in the 'table' variable. You can then add that to the document as you wish. It will also include example text in parenthesis if any available.
精彩评论