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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12470240/
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-26 11:43:05  来源:igfitidea点击:

How to dynamically add anchor/href in jQuery

jquery

提问by thunderousNinja

Im new to jQuery and i'm trying to convert all my phone class to have an anchor with an href:

我是 jQuery 的新手,我正在尝试将我所有的电话类转换为带有 h​​ref 的锚点:

What I have

我拥有的

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

What I want

我想要的是

<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>

I am trying to do something like this, but I am pretty lost:

我正在尝试做这样的事情,但我很迷茫:

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

采纳答案by Vins

I think solution is there in your question only...

我认为解决方案仅在您的问题中...

Have a look at this.

看看这个。

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

FIDDLEHope this is what you want.

FIDDLE希望这是你想要的。

回答by scottmgerstl

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

回答by Gautam3164

Try like this

像这样尝试

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

回答by Rohan Kumar

Write this code like :

编写此代码如下:

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

回答by Ilia Frenkel

Try this:

尝试这个:

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