2013-07-09 111 views
1

下面是簡單/示例表格。 對於問題是我怎麼能爲我需要的特定表單元格放置一個鏈接。 例如,當我點擊桌子上「行1,小區1」的第一個單元格,所以它會執行鏈接,跳轉到下一個站點如何使用jQuery將鏈接添加到表格單元格

<table border="1"> 
    <tr> 
     <td>row 1, cell 1</td> 
     <td>row 1, cell 2</td> 
    </tr> 
    <tr> 
     <td>row 2, cell 1</td> 
     <td>row 2, cell 2</td> 
    </tr> 
</table> 

感謝您的分享。

+1

你試圖執行什麼環節? – tymeJV

+2

將錨標籤放在​​ – commit

+1

之間我無法看到這是如何成爲JQuery的問題。 – jdero

回答

0

你可以給你指定的表格單元格一個id(比如「linker」 ),然後添加一個單擊事件處理程序

jQuery的

$("td#linker").click(function(e) 
{ 
    // Make your content bold 
    $(this).css("font-weight","bold"); 
    // Direct the page like a link 
    window.location.href="<WHER YOU WANT IT TO GO>"; 
    // Prevent the click from going up the chain 
    e.stopPropagation(); 
}); 

HTML

<table border="1"> 
    <tr> 
     <td id="linker">Click Me</td> 
     <td>row 1, cell 2</td> 
    </tr> 
    <tr> 
     <td>row 2, cell 1</td> 
     <td>row 2, cell 2</td> 
    </tr> 
</table> 
5

您需要a標籤:

<td><a href="example.com">row 1, cell 1</a></td> 

只需更換與任何網站,你正試圖鏈接到href值。

更新的jQuery:

如果你想用jQuery做的話,你首先需要某種形式的唯一標識符/選擇器添加到您所需的橫向(如類,或序號位置),然後添加錨標籤。我們只需調用TD選擇 'yourTd' 現在:

var aTag = $('<a>', {href: 'example.com' }); 
aTag.text($('.yourTd').text());// Populate the text with what's already there 

$('.yourTd').text('').append(aTag);// Remove the original text so it doesn't show twice. 
+0

問題是關於如何使用jquery添加鏈接。我假設他已經建立了表結構並需要動態地添加鏈接。 – EmmyS

+0

@EmmyS好的,我會更新我的答案,謝謝。 – Igor

+0

針對jQuery進行了更新。 – Igor

0

這裏是做它的JQuery的操作方法: -

$('<a>',{ 
    text:'row 1, cell 1', 
    href:'http://www.google.com'  
}).appendTo('tr:first td:nth-child(1) '); 

HTML: -

<table border="1"> 
<tr> 
<td></td> 
<td>row 1, cell 2</td> 
</tr> 
<tr> 
<td>row 2, cell 1</td> 
<td>row 2, cell 2</td> 
</tr> 
</table> 

JS FIDDLE

0

首先在你想上,一些環節的HTML td元素添加類如:

<table border="1"> 
    <tr> 
    <td class="link">row 1, cell 1</td> 
    <td>row 1, cell 2</td> 
    </tr> 
    <tr> 
    <td class="link">row 2, cell 1</td> 
    <td>row 2, cell 2</td> 
    </tr> 
</table> 

然後使用jQuery進行內部td元素

$('td.link').each(function() { 
    $(this).html('<a href="google.com">' + $(this).html() + '</a>') 
}); 
0

鏈接如果你想覆蓋TD的使用下面的代碼中的鏈接能力。如果您將通過ajax添加額外的記錄,也可以使用$('body')。

<table class="table"> 
<tbody> 
<tr data-url="/yourlink"> 
<td>test</td> 
<td>test2</td> 
<td class="custom_url"> 
<a href="youroverridelink">link</a> 
</td> 
</tr> 
</tbody> 
</table> 


$(document).ready(function() { 
    $('body').on('click','.table > tbody > tr > td', function() { 
     window.location = $(this).not('.custom_url').parent().data('url'); 
    }); 
}); 
相關問題