2012-08-09 73 views
4

我通過getJSON拉動推文並將它們寫入Google地圖infowindow與JavaScript。問題是,這些推文帶有文本鏈接,但沒有格式(沒有ID /類/任何縮小查找和替換的範圍)。這是我現在使用查找文本代碼搗成泥,但我不能把它包裹不管它發現在<a>標籤正確顯示的鏈接:用jQuery包裝<a>標籤查找並替換

function wrap(str) { 
    return '<a href="' + str + '">' + str + '<\/a>'; 
}; 

function replaceText() { 
    var jthis = $(this); 
    $("*").each(function() { 
     if (jthis.children().length == 0) { 
      jthis.text(jthis.text().replace(/\bhttp[^ ]+/i, wrap)); 
     } 
    }); 
} 
$(document).ready(replaceText); 
$("html").ajaxStop(replaceText); 

難道我忽略的東西或有誰知道更好的方法來做到這一點?

+0

如果你不想使用jQuery這個工作得很好:https://gist.github.com/ryansmith94/0fb9f6042c1e0af0d74f – 2017-10-10 19:28:24

回答

3

如果我理解你的問題的權利,這應該工作。 不確定爲什麼你要迭代元素,因爲正則表達式會掃描所有文本。

<html> 
    <head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> 
     <script> 
     function wrap(str) { 
      return '<a href="' + str + '">' + str + '<\/a>'; 
     }; 
     function replaceText() { 
      $(".tweet").each(function(){ 
       $(this).html($(this).html().replace(/\bhttp[^ ]+/ig, wrap)); 
      }) 

     } 
     $(document).ready(replaceText); 
     </script> 
    </head> 
    <body> 
     <div class="tweet"> test 1 http://example.com/path </div> 
     <div class="tweet"> test 2 http://example.com/path </div> 
    </body> 
</html> 
+0

這絕對是我一直在尋找的,但問題是它是全球性的。我可以解決這個問題,但它仍然會嘗試在頭部中封裝URL(就像那些引用gMaps API的URL一樣)。這是否有一個原因,儘管它應該只是看着「身體」? (將其更改爲文檔也無濟於事)。 – 2012-08-09 16:23:27

+0

我更新了這個例子,這工作正常,沒有弄亂頭部的網址 – Valdis 2012-08-09 16:37:37

+0

就像後續,這是我最終成功使用的: 'function urlwrap(str){return'' + str + ''; }; var text ='data [i] .text.replace(/ \ bhttp [^] +/ig,urlwrap)'' 並且文本var被寫入到信息頁面 - [i] - 從JSON響應。 – 2012-09-04 17:02:47