Javascript 使用 jquery 设置 <td> 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2761234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:49:12  来源:igfitidea点击:

Setting <td> value using jquery

javascriptjqueryhtmldom

提问by timk

I have the div structure shown below. For the second <td>in the table i want to replace &nbsp;with a hyperlink whose href attribute is stored in the variable myLink. How can i do this with jquery ?

我有如下所示的 div 结构。对于<td>表中的第二个,我想替换&nbsp;为一个超链接,其 href 属性存储在变量 myLink 中。我怎样才能用 jquery 做到这一点?

Please help. Thank You.

请帮忙。谢谢你。

<div class="pbHeader">
  <table cellspacing="0" cellpadding="0" border="0">
    <tbody>
         <tr>
             <td class="pbTitle">
               <h2 class="mainTitle">Transfer Membership</h2>
             </td>
             <td>
                    &nbsp;
             </td>
          </tr>
     </tbody>
   </table>
</div>

回答by gnarf

You can do something like this:

你可以这样做:

// you said this was already set
var myLink = 'http://stackoverflow.com/questions/2761234';

var $a = $('<a>').attr('href',myLink).text('My Link!');
$('.pbHeader td:eq(1)').empty().append($a);

This uses the :eq()selector to grab the second TD underneath a .pbHeader(:eq is zero based, so 0 is the first element, 1 is the second element). It empties your &nbsp;and appends the generated <a>tag inside of it.

这使用:eq()选择器来获取 a 下面的第二个 TD .pbHeader(:eq 是从零开始的,所以 0 是第一个元素,1 是第二个元素)。它清空您的&nbsp;并将生成的<a>标签附加到其中。

You could also do this:

你也可以这样做:

$('.pbHeader td:eq(1)').html('<a href="'+myLink+'">My Text!</a>');

Which sets the innerHTML of that <td>to be your "link"

这将其innerHTML设置<td>为您的“链接”

jsbin preview

jsbin 预览