Showing dynamic links inside a table

我怕爱的太早我们不能终老 提交于 2021-01-28 08:40:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!