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

问题描述:

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

Replace all href's within a div element by adding http://mysite.com?url= infront for example. if the html is...

<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>

通过在前面添加 http://mysite.com?url=

替换每个href. html将是...

replace each href by adding http://mysite.com?url= infront so the outcome of the html will be...

<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>

使用 jQuery.each

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

示例