2010-09-01 42 views
2

IST有什麼更好的辦法來替代/包的H TP://name.tld/request_url參數或H TPS://name.tld/request_url在一定的HTML元素參數文本與<a href>jQuery:用<a href="this">...</a>替換()或包裝()http://name.tld/request_url?參數?

HTML

<div id="posts"> 
    <div class="post"> 
    Tweet text 1 http://google.com and other text. 
    </div> 
    <div class="post"> 
    Tweet text 2 https://www.google.com and other text. 
    </div> 
    <div class="post"> 
    Tweet text 3 
    </div> 
    <div class="post"> 
    ... 
    </div> 
</div> 

的JavaScript

jQuery('#posts .post').each(function() { 
elem = jQuery(this); 
elem.html(
    elem.text() 
    .replace(/(http?:\/\/?\S+)/g, "<a href='$1'>$1</a>") 
); 
}); 

任何jQuery.wrap()替代將是不錯太...

回答

4

沒有一種更好的方式,但你可以把它簡化一下,像這樣:

jQuery('#posts .post').each(function() { 
    jQuery(this).html(function(i, html) { 
    return html.replace(/(http?:\/\/?\S+)/g, "<a href='$1'>$1</a>"); 
    }); 
}); 

使用這種方法只有如果您確定帖子中不包含HTML,否則請使用您擁有的內容。

jQuery適用於DOM節點,而不是節點內的文本,或者確實如此,因爲它只是JavaScript ......但它並沒有提供很多額外的功能。包括.wrap()在內的jQuery專注於DOM操作,而不是文本。

+0

你是對的 - wrap()對純文本不起作用, 如果節點內可能有其他HTML代碼,則不應使用text()。 我的問題只是,是否有任何方法可以用較少的代碼/ efford來做到這一點?代碼可以更早地被操縱。服務器端或AJAX調用的響應成功函數。 Thx爲您的答案無論如何... – gabel 2010-09-01 12:58:40

+0

@gabel - 沒有真正的更便宜的方式,我見過,除非你提前做服務器端(我會)。 – 2010-09-01 13:07:59