2012-08-08 47 views
0

我正在尋找添加一個屬性(href)到一個表的td。jQuery添加href字符串

我想jQuery會工作!

我需要幫助,請...

網址:http://mysite

原始表:

<table> 
    <thead> 
     <tr> 
      <th>Type</th> 
      <th>Name</th> 
      <th>Url</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr class='Collection'> 
      <td>Collection</td> 
      <td>Collection1</td> 
      <td>/Collection1</td> 
     </tr> 
     <tr class='Site'> 
      <td>Site</td> 
      <td>Site1</td> 
      <td>/site1</td> 
     </tr> 
    </tbody> 
</table> 

那麼結果將是:

<table> 
    <thead> 
     <tr> 
      <th>Type</th> 
      <th>Name</th> 
      <th>Url</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr class='Collection'> 
      <td>Collection</td> 
      <td>Collection1</td> 
      <td><a href="http://mysite/Collection1">/Collection1</a></td> 
     </tr> 
     <tr class='Site'> 
      <td>Site</td> 
      <td>Site1</td> 
      <td><a href="http://mysite/site1">/site1</a></td> 
     </tr> 
    </tbody> 
</table> 
+2

td沒有href屬性。 – eugeneK 2012-08-08 12:09:17

+0

我試過$(「td:eq(2)」)。each(function(){(').appendTo('td') 但它沒有工作 – user472285 2012-08-08 12:13:57

+0

你應該追加到$這個)。因爲每個循環思考tds的列表 – eugeneK 2012-08-08 12:18:18

回答

0

假設你的意思是「將一個鏈接添加到表格的td「,試試這個:

$('table tbody tr').each(function() { 
    var cell = $('td:last', this), 
     url = $(cell).text(); 

    $(cell).wrapInner('<a href="' + url + '">'); 
})​ 

演示:http://jsfiddle.net/4hMey/1/

+0

你想要'wrapInner',而不是'wrap',因爲'wrap'會使'a'標記父節點和'td'標籤給子節點 – amurra 2012-08-08 12:30:08

+0

@amurra好的調用!修正了,謝謝! – 2012-08-08 12:33:33

0

給你想改變一個類的TD這樣你就可以用jQuery輕鬆地選擇它們,然後更改HTML內容。

<td class="MYCLASS"><a href="http://mysite/site1">/site1</a></td> 


$('.MYCLASS').each(function() { 
    var text = $(this).html(); 
    $(this).html('<a href="http://mysite' + text + '">' + text + '</a>'); 
}); 
0

如果你總是知道,最後TD需要的鏈接,那麼你可以做這樣的事情:

var urlTd = $('table tbody td:last-child'); 
urlTd.wrapInner('<a href="http://mysite' + urlTd.html() + '" />'); 

這裏是展示它的工作一個jsFiddle