将TD改为链接

时间:2015-07-06 21:59:44

标签: javascript jquery

<table>
    <tbody>
        <tr>
            <td>Test 1</td>
            <td>Test 2</td>
        </tr>
    </tbody>
</table>

html在上面。我尝试了很多不同的方法将Test2更改为一个链接,但没有成功。 Test1保持不变但Test2发生变化。我的目标是将Test2或其中的任何内容(它更改)更改为可点击的Google搜索链接。因此,Test2将成为http://www.google.com/search?hl=en&q=Test的链接2. jquery或javascript很好。

4 个答案:

答案 0 :(得分:2)

使用原生Javascript函数:

&#13;
&#13;
// 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>'; 
&#13;
<table>
    <tbody>
        <tr>
            <td>Test 1</td>
            <td>Test 2</td>
        </tr>
    </tbody>
</table>
&#13;
&#13;
&#13;

使用jQuery:

&#13;
&#13;
// 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>');
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在第二个td(从0开始)使用html方法:

&#13;
&#13;
$('td').eq(1).html(function(_, s) {
  return '<a href="http://www.google.com/search?hl=en&q=' + s + '">' + s + '</a>';
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

&#13;
&#13;
var test = $('td:nth-child(2)')
$(test).wrapInner('<a href="http://www.google.com/search?hl=en&q=' + test.html() + '"></a>');
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

当您单击单元格时,这会将单元格转换为可单击的链接。

jsFiddle Demo

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