用jquery中的链接href值替换link的文本

时间:2014-07-10 07:35:47

标签: jquery html

我想用链接href值替换链接的文本。

我在表格中有1000个链接。

HTML

<td  valign="middle"class="link2"align="left" width="auto" >
<a href="http://www.example1.com" target="_blank">Item1</a>
</td>
<td  valign="middle"class="link2"align="left" width="auto" >
<a href="http://www.example2.com" target="_blank">Item2</a>
</td>
.
.
.
.

我想用链接href值Item1 Item2 ...

替换文本值http://www.example1.com http://www.example1.com ...

我正在尝试这种方式,但它不起作用。

jquery的

$('.link2 a').html($(this).attr('href'));
//also tried like this.
$('.link2 a').html(this.attr('href'));

$('.link2 a').text($(this).attr('href'));
//also tried like this.
$('.link2 a').text(this.attr('href'));

请建议如何做到这一点。

感谢。

7 个答案:

答案 0 :(得分:4)

使用html()的回调函数,即.html( function ).text( function )

<强> Live Demo

$('.link2 a').html(function(){
   return this.href;
});

答案 1 :(得分:2)

这里this不是指锚。遍历每个锚节点并设置其文本。试试这段代码

 $('.link2 a').each(function(){
   $(this).text($(this).attr('href'));
 });

答案 2 :(得分:1)

尝试此操作:您需要迭代每个锚标记,因为您需要读取每个锚标记href值并将其设置为文本。

$('.link2 a').each(function(){
  $(this).text($(this).attr('href'));
});

答案 3 :(得分:1)

使用此

$('.link2 a').each(function(){
  $(this).html($(this).attr('href'));
});

答案 4 :(得分:1)

试试这个:

$('.link2').each(
 function(index)
 {
   $(this).children(":first").text($(this).attr('href'));
 }


);

答案 5 :(得分:1)

试试这个:

$('.link2 a').each(function(){
  $(this).text($(this).attr('href'));
});

答案 6 :(得分:0)

在代码下方轻松使用

    $('.link2 a').each(function(){
   $(this).text($(this).attr('href'));
 });
相关问题