gpt4 book ai didi

jquery - 将 的文本转换为超链接

转载 作者:太空狗 更新时间:2023-10-29 13:35:23 26 4
gpt4 key购买 nike

更新:
答案 #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 (获胜者)
  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

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

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

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

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

我需要将其更改为:

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

最佳答案

试试这个:

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

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

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

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

如果它是包含链接的整个,那么您将希望对所有其他匹配项进行操作。通过附加 :even 来做到这一点到你的选择器,像这样:

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

(是的,:even 而不是 :odd 来选择第一、第三等元素,因为索引是基于 0 的。)

关于jquery - 将 <span> 的文本转换为超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5215316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com