javascript JQuery 添加文本链接

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

JQuery add link to text

javascriptjqueryjquery-plugins

提问by van

Is there a way in JQuery to select text from the html document and add a link around it?

JQuery 有没有办法从 html 文档中选择文本并在它周围添加一个链接?

Many Thanks, Nav

非常感谢,导航

采纳答案by kobe

you can do it like below.

你可以像下面那样做。

var txtN=$("#div").text();
var htmlStr=<a href="">txtN</a>

then inject htmlStr in the HTML...

然后在 HTML 中注入 htmlStr ...

you can use the absolute positioning to set the position.

您可以使用绝对定位来设置位置。

回答by Jacob Relkin

You can use jQuery's wrapfunction:

您可以使用 jQuery 的wrap功能:

$(someSelector).wrap(function() {
   var link = $('<a/>');
   link.attr('href', 'somewhere_far_far_away');
   link.text($(this).text());
   return link;
});

回答by Banago

This is how I do it. Let's suppose you need to do this on a h3 tag:

我就是这样做的。假设您需要在 h3 标签上执行此操作:

var h3tag = $('h3#head');
var txt = h3tag.text();
h3tag.text(''); //Remove default text
$("<a />", {
   "href" : $('h2 a').attr('href'), //grab the link from somewhere
   "text" : txt
}).appendTo(h3tag);

I hope it helps.

我希望它有帮助。