jQuery 将 <span> 的文本转换为超链接

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

Convert a <span>'s text into a hyperlink

jqueryhtmlhyperlink

提问by ox4dboy

UPDATE:
Answer #3 ended up working the best. I most likely did something wrong with the other suggestions; #3 was maybe the easiest to implement. If you are curious, the example solutions that I tried can be found here (for now):

更新:
答案 #3 最终效果最好。我很可能在其他建议上做错了;#3 可能是最容易实现的。如果您好奇,可以在此处(目前)找到我尝试过的示例解决方案:

  1. http://dl.dropbox.com/u/1007716/spanToUrl/test01.html
  2. http://dl.dropbox.com/u/1007716/spanToUrl/test02.html
  3. http://dl.dropbox.com/u/1007716/spanToUrl/test03.html(winner)
  4. http://dl.dropbox.com/u/1007716/spanToUrl/test04.html
  5. http://dl.dropbox.com/u/1007716/spanToUrl/test05.html
  6. http://dl.dropbox.com/u/1007716/spanToUrl/test06.html
  1. http://dl.dropbox.com/u/1007716/spanToUrl/test01.html
  2. http://dl.dropbox.com/u/1007716/spanToUrl/test02.html
  3. http://dl.dropbox.com/u/1007716/spanToUrl/test03.html(获胜者)
  4. http://dl.dropbox.com/u/1007716/spanToUrl/test04.html
  5. http://dl.dropbox.com/u/1007716/spanToUrl/test05.html
  6. http://dl.dropbox.com/u/1007716/spanToUrl/test06.html

ORIGINAL POST:
I have a plain text website address inside a <span>tag. I'd like to change that <span> tag into a proper hyperlink with target="_blank"

原始帖子:
我在<span>标签中有一个纯文本网站地址。我想将该 <span> 标记更改为适当的超链接target="_blank"

I've put together a detailed example of what I have to work with here: http://bit.ly/spantourl

我在这里整理了一个我必须使用的详细示例:http: //bit.ly/spantourl

If you don't want to click through, here is what I have:

如果你不想点击,这是我有的:

<span>http://www.domain.com/about</span>

and I need to change that into:

我需要将其更改为:

<a href="http://www.domain.com/about" target="_blank">http://www.domain.com/about</a>

回答by Ori

Try this:

尝试这个:

$('.sampleClass span').replaceWith(function() {
    var url = $.trim($(this).text());
    return '<a href="' + url + '" target="_blank">' + url + '</a>';
});

There's no need for each, since replaceWith can iterate through multiple elements and can take a function as a parameter.

不需要each,因为 replaceWith 可以遍历多个元素并且可以将函数作为参数。

Looking at your sample HTML, I see that it is only the first <td>that contains a URL. If there is indeed only one, you can add first()to the selector chain, like this:

查看您的示例 HTML,我发现它只是第一个<td>包含 URL。如果确实只有一个,则可以添加first()到选择器链中,如下所示:

$('.sampleClass span').first().replaceWith( /* ... */ );

If it is rather the entire columnthat contains links, than you'll want to operate on every other match. Do this by appending :evento your selector, like this:

如果它是包含链接的整个,那么您将希望对所有其他匹配项进行操作。通过附加:even到您的选择器来执行此操作,如下所示:

$('.sampleClass span:even').first().replaceWith( /* ... */ );

(Yes, :evenand not :oddto select the 1st, 3rd, &c. elements, because of 0-based indexing.)

(是的,因为基于 0 的索引,所以:even不要:odd选择 1st、3rd 和 c. 元素。)

回答by rahul

Put the span an id and then you can do something like

把跨度一个 id 然后你可以做类似的事情

var linkText = $("#yourspanid").text();

$("<a/>").attr({"href": linkText, "target": "_blank"}).text(linkText).appendTo("body");
$("#yourspanid").remove();

Changing according to your edit

根据您的编辑更改

var elems = $("span.myClass > span");
elems.each(function(){
    var linkText= $(this).text();
    $("<a/>").attr({"href": linkText, "target": "_blank"}).text(linkText).appendTo("body");
});
elems.remove();

See a working demo

查看工作演示

回答by Simon H

You need to have some form of identification in order to do the conversion from node A to node B. I would suggest something along the following lines:

您需要有某种形式的标识才能进行从节点 A 到节点 B 的转换。我会建议以下几行:

The JQuery code:

JQuery 代码:

<script type="text/javascript">

    $('.convertableIdentifier').each(function(i, el) {

        // grab the url and the link text
        var url = $(el).html();

        // create a new node with query by decorating a
        // empty a tag
        var newNode = $('<a></a>').attr('href', url).attr('target', '_blank').html(url);

        // replace the current node with our new node
        $(el).replaceWith(newNode);

    });

</script>

The HTML:

HTML:

<span class="convertableIdentifier">http://www.google.com</span>
<span class="convertableIdentifier">http://www.youtube.com</span>
<span class="convertableIdentifier">http://www.facebook.com</span>

The above code is not tested, but should hopefully lead you in the right direction.

上面的代码没有经过测试,但应该可以引导你走向正确的方向。

回答by Rob Lee

Use jQuery.

使用 jQuery。

give the span an id:

给 span 一个 id:

<span id="linkChange">http://domain.com</span>

jQuery code:

jQuery代码:

var href = jQuery('#linkChange').html();
var link = "<a href='"+href+"' target='_blank'>"+href+"</a>";

jQuery('#linkChange').replaceWith(link);

回答by Michael Jasper

Perhaps something like this: (no need to know ids/classes) useing jquerys for-each loop and specificly target spans inside of tds

也许是这样的:(不需要知道 ids/classes)使用 jquerys for-each 循环并专门针对 tds 内的跨度

$(document).ready(function(){ $('td span').each(function(){ $(this).text("" + $(this).text() + ""); }); });

$(document).ready(function(){ $('td span').each(function(){ $(this).text("" + $(this).text() + ""); }) ; });

EDIT:this code works much better:

编辑:此代码效果更好:

<script type="text/javascript">
    $(document).ready(function(){
        $('td span').each(function(){
            $(this).html("<a href='" + $(this).html() + "' />" + 
                $(this).html() + "</a>");
        });
    });
</script>

The origional used the .text()function of jquery which html escaped the <>characters, unintentionally addin &GT; &LT;into the dom, while .html actually outputs the correct tags

原文使用.text()jquery的功能,html转义<>字符,无意中addin&GT; &LT;到dom中,而.html却输出了正确的标签