make keyword into link automatically, globally

雨燕双飞 提交于 2019-11-30 19:23:25

very very simple example...

jQuery

var span = $('span');
    span.html(function(i,html){
        replaceTextWithHTMLLinks(html);
    }); // jQuery version 1.4.x


function replaceTextWithHTMLLinks(text) {
  var exp = /(apple)/ig;
    return text.replace(exp,"<a class='link' href='http://www.$1.com' target='_blank' >$1</a>"); 
}

html

<span> 
An apple a day, makes 7 apples a week!
</span>

demo

Here's a simple jQuery plugin that should do the trick. It will only select text nodes so that if you have an element with a class apple or id apple it won't get replaced. Additionally, if you have a link <a href="#">apple</a> it won't get replaced (might be a little more than you need, but I thought I'd post it anyway):

(function($) {
    $.fn.replacetext = function(target, replacement) {
         // Get all text nodes:
         var $textNodes = this
                 .find("*")
                 .andSelf()
                 .contents()
                 .filter(function() {
                     return this.nodeType === 3 &&
                         !$(this).parent("a").length;
                 });

         // Iterate through the text nodes, replacing the content
         // with the link:
         $textNodes.each(function(index, element) {
             var contents = $(element).text();
             contents = contents.replace(target, replacement);
             $(element).replaceWith(contents);
         });
    };
})(jQuery);

Usage:

$("body").replacetext(/apple/gi, "<a href='http://www.$&.com'>$&</a>");

Working example: http://jsfiddle.net/andrewwhitaker/VmHjJ/

Note that this could become inefficient rather quickly due to the use of the $("*") selector. If possible, you should replace it with something more specific (or remove the .find("*").andSelf() portion entirely and pass the plugin a more specific selector).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!