2011-01-20 71 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); 
      } 
     }); 
    }