问题
In jquery, how can I show a link that is generated on the fly inside a table?
I will have the link stored in my database, but I want it to be shown by a name and then take me to the correct link accordingly.
I have an array of strings like [ {Name1:Link1} ]
stored, and I want it to be shown inside the table as Name1
linking to Link1
.
Please tell me how to do so.
回答1:
You need to store them in a (object) map instead of an array.
var linksMap = {
'google': 'http://google.com',
'stackoverflow': 'http://stackoverflow.com',
'jquery': 'http://jquery.com'
};
Then, assuming that you've the following table,
<table id="links">
<tr><td>google</td></tr>
<tr><td>stackoverflow</td></tr>
<tr><td>jquery</td></tr>
</table>
you can use the following jQuery script to create links and put them in the cells:
$('#links>tbody td:nth-child(1)').each(function() {
var $td = $(this);
var name = $td.text();
var link = linksMap[name];
var $a = $('<a>').attr('href', link).text(name);
$td.html($a);
});
来源:https://stackoverflow.com/questions/5765676/showing-dynamic-links-inside-a-table