如何使用 jQuery 将单词替换为 url/url?
我想使用 jQuery 将特定单词(laptop、asus、acer)替换为链接(test.com/l12、test.com/13、test.com/14)。 我发现了这个功能
<script type="text/javascript">
(function($) {
var thePage = $("body");
thePage.text(thePage.html().replace(/laptop/ig, '<a href="http://test.com/laptop">laptop</a>'));
})(jQuery)
</script>
,但问题是它替换了现有网址中的笔记本电脑单词(如果网址是 test.com/laptop-review,则创建像 test.com/test.com/laptop-review 这样的网址)和所有笔记本电脑 html (html页面上的 ids、classes、url 等)被破坏。
谢谢
I want to replace specific words (laptop, asus, acer) with links (test.com/l12, test.com/13, test.com/14) using jQuery.
I found this function
<script type="text/javascript">
(function($) {
var thePage = $("body");
thePage.text(thePage.html().replace(/laptop/ig, '<a href="http://test.com/laptop">laptop</a>'));
})(jQuery)
</script>
but the problem is that it replaces laptop word in existing urls (creating urls like test.com/test.com/laptop-review if the url was test.com/laptop-review) and all the laptop html (html ids, classes, urls etc) on the page is destroyed.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
fiddle http://jsfiddle.net/LXw6P/
编辑当然你可以使它成为一个函数并重用它:
使用它:
You could do:
fiddle http://jsfiddle.net/LXw6P/
EDIT of course you could make this a function and reuse it:
use it:
您可以尝试使用 jQuery 文本替换插件 - http:// /net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
该插件应忽略 HTML 标记并仅更改“文本”值。
此问题中给出了更多详细信息 - 如何对单词进行不区分大小写的搜索并使用 jquery 将其转换为超链接?
You could try using the jQuery text replace plug-in - http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
The plug-in should ignore HTML mark-up and only change 'text' values.
Further details are given in this question - How do I do a case insensitive search for a word and convert it to a hyperlink using jquery?