开发者

make keyword into link automatically, globally

开发者 https://www.devze.com 2023-02-06 09:44 出处:网络
is there a way to make a every instance of a word automatically turn into a link?开发者_如何转开发

is there a way to make a every instance of a word automatically turn into a link?

开发者_如何转开发

so for instance, everytime I write "apple", it is automatically formatted to <a href="www.apple.com" class="whatever" target="_blank">apple</a>

I'm assuming i could use javascript or possibly jquery.

thanks!


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消