如何替换所有< a> div元素内的hrefs? [英] how to replace all <a> hrefs within div element?

查看:94
本文介绍了如何替换所有< 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);
})

示例

这篇关于如何替换所有&lt; a&gt; div元素内的hrefs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆