2013-07-09 113 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'); 
    }); 
}); 
相关问题