2010-09-01 67 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