0

我想使用 jQuery 将特定单词(笔记本电脑、华硕、宏碁)替换为链接(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>

但问题是它替换了现有 url 中的笔记本电脑单词(如果 url 是 test.com/laptop-review,则创建诸如 test.com/test.com/laptop-review 之类的 url)和所有笔记本电脑 html(html id、类、页面上的 urls 等)被破坏。

谢谢

4

2 回答 2

3

你可以这样做:

$('body *').each(function(){
     var txt = $(this).text();

    txt =  txt.replace('laptop', '<a href="http://test.com/laptop">laptop</a>');


    $(this).html(txt);
});

小提琴http://jsfiddle.net/LXw6P/

编辑当然你可以把它变成一个函数并重用它:

var updateTxt = function(stringToReplace){
    var replaceText = '<a href="http://test.com/'+stringToReplace'+">'+stringToReplace+'</a>';
    $('body *').each(function(){
       var txt = $(this).text();

        txt =  txt.replace(stringToReplace, replaceText);


        $(this).html(txt);
    });
}

用它:

updateTxt('laptop');
于 2011-09-29T08:44:37.343 回答
1

您可以尝试使用 jQuery 文本替换插件 - http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/

插件应忽略 HTML 标记,仅更改“文本”值。

此问题中提供了更多详细信息-如何对单词进行不区分大小写的搜索并使用 jquery 将其转换为超链接?

于 2011-09-29T08:47:31.067 回答