2011-01-20 3 views
0

私のページのすべてのURLにハイパーリンクを作成しようとしています。 は、このようなコードがあります:Html URL上にハイパーリンクを作成します。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> 

と私はコンテンツページ内のすべてのURLにリンクを追加するにはjavascript関数の下に使用:上記のコードで

<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

答えて

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); 
      } 
     }); 
    } 
0

あなたのタグにIDを入れて、あなたが.each()を使用しているので、それがあなたのjQueryを使って

1. <a id="target" href="your/target/url"> 
2. ${"#target"}.attr('href','new/target/url') 

それを一致させます。複数回変更する場合は、タグのクラス属性を使用します。

関連する問題