简体   繁体   中英

How to set hyperlink for first column cell from value of second column cell

I'm using generated table and need for first column cells to have hyperlinks that ar in second column. Is it achievable with JavaScript?

 $('table.one').each(function() { var a1 = $(this).closest('tr').find('td:eq(0)').text(); var a2 = $(this).closest('tr').find('td:eq(1)').text(); $(this).innerHtml = '<a href="' + a2 + '">' + a1 + '</a>'; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> <tr> <td class="one">text1</td> <td class="two">link1.com</td> <td class="three"> text13</td> </tr> <tr> <td class="one">text2</td> <td class="two">link2.com</td> <td class="three">text23</td> </tr> </tbody> </table>

You can achieve this using .html() like below:

 $('table.one').each(function() { var a1 = $(this).closest('tr').find('td:eq(0)').text(); var a2 = $(this).closest('tr').find('td:eq(1)').text(); $(this).html('<a href="' + a2 + '">' + a1 + '</a>'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> <tr> <td class="one">text1</td> <td class="two">link1.com</td> <td class="three"> text13</td> </tr> <tr> <td class="one">text2</td> <td class="two">link2.com</td> <td class="three">text23</td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM