【问题标题】:How to replace word/words with url/urls using jQuery?如何使用 jQuery 用 url/urls 替换单词/单词?
【发布时间】:2011-09-29 08:21:32
【问题描述】:

我想使用 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 , classes, urls etc) 被销毁。

谢谢

【问题讨论】:

  • replace(/^laptop/ig,... 或者你可以试试replace(/laptop\s/ig, 所以任何后面跟空格的单词都不能包含空格
  • 从来没有想过这个。我会试试的

标签: jquery url replace word words


【解决方案1】:

你可以这样做:

$('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');

【讨论】:

  • 这很好,但遍历每个元素是一项令人筋疲力尽的任务。 :) 也许在特殊词中添加一个特殊的类和跨度可以减轻工作量:)
【解决方案2】:

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

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

此问题提供了更多详细信息 - How do I do a case insensitive search for a word and convert it to a hyperlink using jquery?

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多