2011-01-20 103 views
0

我想在我的网页上的每个网址做一个超链接。 有这样的代码:创建超链接的Html URL与JQuery的除了IMG SRC链接

<div id="divC"> 
     Hello testing message 
     My profile link : http://stackoverflow.com/users/568085/abhishek and 
     my user account link : 
    <a href="http://stackoverflow.com/users/568085/abhishek"> 
    <img height="58" width="208" title="Stack Overflow profile for Abhishek at Stack Overflow, Q&amp;A for professional and enthusiast programmers" alt="Stack Overflow profile for Abhishek at Stack Overflow, Q&amp;A for professional and enthusiast programmers" src="http://stackoverflow.com/users/flair/568085.png?theme=dark"> 
    </a> 
</div> 

,我用javascript函数下面的内容页面上的每个URL添加链接:

<script> 
    //call function for linking every url 
    createLinks(); 
    function createLinks() 
    { 
     var exp=/(((\b(https?|ftp|file):\/\/))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;  
     $("div#divC").each(function(index) {    
      $(this).html($(this).html().replace(exp, "<a target='_self' class='msg_links' href=$1>$1</a>")); 
     }); 
    } 
     </script> 

在上面的代码工作正常,但我不希望创建链接上<img src='www.test.com'>。 当我运行这一点,在<img src="<a href='www.test.com'>www.test.com</a>" >还创建的链接,
我怎样才能避免<img> SRC创建链接?

+0

你应该能够调整你的正则表达式来实现这一点。 – Malk 2011-01-20 07:47:47

回答

1

啊......我明白你在做什么。我前一阵子做了一个插件,取代了笑脸:D。这段代码是否工作得更好?

//call function for linking every url 
    createLinks(); 


    function createLinks() 
    { 
     var exp=/(((\b(https?|ftp|file):\/\/))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;  


     $("div#divC") 
     .contents() 
     .filter(function() { 

      if (typeof (Node) == 'undefined') { 
       return this.nodeType == 3; 
      } 
      else { 
       return this.nodeType == Node.TEXT_NODE; 
      } 
     }).each(function(index) { 

      var x = $(this)[0].nodeValue; 
      if (x != '') { 
       x = x.replace(exp, "<a target='_self' class='msg_links' href='$1'>$1</a>"); 
       $(this).replaceWith(x); 
      } 
     }); 
    }