如何替换div元素中的所有<a> hrefs?

Yus*_*liq 2 javascript jquery replace href

例如,通过添加http://mysite.com?url= infront 替换div元素中的所有href .如果HTML是...

<div class="post-body">
<a href="http://www.google.com">google</a>
<a href="http://www.youtube.com">youtube</a>
<a href="http://www.facebook.com">facebook</a>
</div>
Run Code Online (Sandbox Code Playgroud)

通过添加http://mysite.com?url= infront来替换每个href,这样html的结果将是......

<div class="post-body">
<a href="http://mysite.com?url=http://www.google.com">google</a>
<a href="http://mysite.com?url=http://www.youtube.com">youtube</a>
<a href="http://mysite.com?url=http://www.facebook.com">facebook</a>
</div>
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 6

使用jQuery.each

$('.post-body a').each(function () {
    var $this = $(this),
        href = $this.attr('href');
    $this.attr('href', "http://mysite.com/?url=" + href);
})
Run Code Online (Sandbox Code Playgroud)