如何在jQuery中动态添加anchor / href

时间:2012-09-18 04:07:50

标签: jquery

我是jQuery的新手,我正在尝试将我的所有手机类转换成一个带有href的锚:

我有什么

<div class="phone">111-111-1111</div>
<div class="phone">666-555-4444</div>

我想要什么

<div class="phone"><a href="tel:111-111-1111">111-111-1111</a></div>
<div class="phone"><a href="tel:666-555-4444">666-555-4444</a></div>

我正在尝试做这样的事情,但我很遗憾:

$('.phone').each(function(){
  $(this).wrapInner('<a name="???' + $(this).html() + '" />');
});

5 个答案:

答案 0 :(得分:6)

我认为解决方案只在你的问题中......

看看这个。

$('.phone').each(function(){
    $(this).wrapInner('<a href="tel:' + $(this).html() + '" />');
});​

FIDDLE 希望这就是您想要的。

答案 1 :(得分:5)

$(".phone").each(function(index, element){
    $(element).html($("<a></a>").attr("href", $(element).text()).text($(element).text()));
});

答案 2 :(得分:2)

试试这个

$('.phone').each(function(){
   $(this).append('<a href="' + $(this).html() + '">'+$(this).html()+'</a>');
});

答案 3 :(得分:2)

将此代码写为:

$('.phone').each(function(){
    $(this).html('<a href="tel:' + $(this).html() + '">'+$(this).html()+'</a>');
});

答案 4 :(得分:1)

试试这个:

$('.phone').each(function(){
  $(this).html('<a name="???' + $(this).html() + '" href="tel:'+$(this).html()+'">'+$(this).html()+'</a>');
});
相关问题