jQuery 如何使用jquery在div内添加文本链接?

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

how to add text link inside a div using jquery?

javascriptjqueryhtmlhref

提问by user2773294

I want to place some text as link inside a div.

我想在 div 中放置一些文本作为链接。

For example, I want to place text 'Google' with hyperlink <a href="http://www.google.com"inside a div having class-id as "my-link".

例如,我想将带有超链接的文本 'Google'<a href="http://www.google.com"放在 class-id 为“my-link”的 div 中。

How can this be done using jquery or javascript?

如何使用 jquery 或 javascript 完成此操作?

回答by Sergio

Class and ID is not the same.

Class 和 ID 不一样。

If ID try this:

如果 ID 试试这个:

$('#my-link').html('<a href="http://www.google.com">Google</a>');

Demo with ID

带 ID 的演示

If Class try this:

如果 Class 试试这个:

$('.my-link').html('<a href="http://www.google.com">Google</a>');
   ^

Demo with class

课堂演示

回答by Subin

You can do this :

你可以这样做 :

$('.my-link').html('<a href="http://www.google.com">Google</a>');

but it would add hyperlink to all .my-linkdivs, so it's better to add an IDto div and use the IDon jQuerycode.

但它会向所有.my-linkdiv添加超链接,因此最好向 div添加一个ID并在jQuery代码上使用该ID

回答by Arun P Johny

If my-linkis the class of the target div then

如果my-link是目标 div 的类,则

$('.my-link').html(function(idx, html){
    return html.replace(/Google/g, '<a href="http://www.google.com">Google</a>')
})

Demo: Fiddle

演示:小提琴