最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to replace all <a> hrefs within div element? - Stack Overflow

programmeradmin1浏览0评论

Replace all href's within a div element by adding = infront for example. if the html is...

<div class="post-body">
<a href="">google</a>
<a href="">youtube</a>
<a href="">facebook</a>
</div>

replace each href by adding = infront so the oute of the html will be...

<div class="post-body">
<a href="://www.google">google</a>
<a href="://www.youtube">youtube</a>
<a href="://www.facebook">facebook</a>
</div>

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

<div class="post-body">
<a href="http://www.google.">google</a>
<a href="http://www.youtube.">youtube</a>
<a href="http://www.facebook.">facebook</a>
</div>

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

<div class="post-body">
<a href="http://mysite.?url=http://www.google.">google</a>
<a href="http://mysite.?url=http://www.youtube.">youtube</a>
<a href="http://mysite.?url=http://www.facebook.">facebook</a>
</div>
Share Improve this question asked Oct 25, 2011 at 16:48 Yusaf KhaliqYusaf Khaliq 3,39311 gold badges45 silver badges82 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

Using jQuery.each

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

Example

You can use directly the .attr() method

$('.post-body a').attr('href', function(i, currentValue){
   return 'http://mysite.?url=' + currentValue;
});

Demo at http://jsfiddle/gaby/94Bf4/

Use jQuery's $.each method: http://jsfiddle/bFEzt/

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

simple

$.each("a",function(index, elem){
    $(elem).attr('href','http://mysite.?url=' + $(elem).attr('href'));
});

You can do this in one line of code with replace:

$('div.post-body').html(
    $('div.post-body').html().replace(/href="/g,'href="http://mysite.?url=') 
);
发布评论

评论列表(0)

  1. 暂无评论