将TD更改为链接

Changing TD into a link

本文关键字:链接 TD      更新时间:2023-09-26
<table>
    <tbody>
        <tr>
            <td>Test 1</td>
            <td>Test 2</td>
        </tr>
    </tbody>
</table>

html在上面。我尝试了许多不同的方法将Test2更改为链接,但都没有成功。Test1保持不变,但Test2发生变化。我的目标是改变Test2或任何可能在(它改变)成一个可点击的谷歌搜索链接。Test2会变成http://www.google.com/search?hl=en&q=Test 2的链接。Jquery或javascript都可以

使用原生Javascript函数:

// Select the second TD (you might want to use an ID instead)
var myTD = document.getElementsByTagName('td')[1];
// Change its content
myTD.innerHTML = '<a href="http://www.google.com/search?hl=en&q=' + myTD.textContent + '">'
               +     myTD.textContent
               + '</a>'; 
<table>
    <tbody>
        <tr>
            <td>Test 1</td>
            <td>Test 2</td>
        </tr>
    </tbody>
</table>

使用jQuery:

// Select the second TD (you might want to use an ID instead)
var myTD = $('td:eq(1)');
// Change its content
myTD.html('<a href="http://www.google.com/search?hl=en&q=' + myTD.text() + '">'
        +     myTD.text()
        + '</a>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <td>Test 1</td>
            <td>Test 2</td>
        </tr>
    </tbody>
</table>

在第二个td(基于0)上使用 html 方法:

$('td').eq(1).html(function(_, s) {
  return '<a href="http://www.google.com/search?hl=en&q=' + s + '">' + s + '</a>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>Test 1</td>
      <td>Test 2</td>
    </tr>
  </tbody>
</table>

var test = $('td:nth-child(2)')
$(test).wrapInner('<a href="http://www.google.com/search?hl=en&q=' + test.html() + '"></a>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>Test 1</td>
      <td>Test 2</td>
    </tr>
  </tbody>
</table>

当你点击单元格时,它会将单元格转换成一个可点击的链接。

<<p> jsFiddle演示/strong>
$('td').click(function(){
    tmp = $(this).text();
    $(this).html('<a href="http://www.google.com/search?hl=en&q='+tmp+'" >'+tmp+'</a>');
});