替换DIV中的所有URL

时间:2016-10-26 15:14:02

标签: javascript jquery html

我想修改指定DIV中的所有网址但不确定如何操作。我想要的一个例子是:

<div id="SearchList">
<a href="www.google.com/up">up</a>
<a href="www.google.com/down">down</a>
<a href="www.google.com/left">left</a>
<a href="www.google.com/right">right</a>
</div>

例如,我想修改要显示的URL如下:

<div id="SearchList">
<a href="www.bing.com/up">up</a>
<a href="www.bing.com/down">down</a>
<a href="www.bing.com/left">left</a>
<a href="www.bing.com/right">right</a>
</div>

有关如何实现这一目标的任何想法?

3 个答案:

答案 0 :(得分:5)

// For each anchor element...
$("#SearchList a").each(function() { 

    // Change its 'href' attribute to...
    $(this).attr("href", 

        // Its current 'href' attribute with a .replace() called
        $(this).attr("href").replace("google", "bing")); 
});

答案 1 :(得分:1)

这就是我要做的事情

$('#SearchList a').each(function(){

    var $el = $(this),
        hash = $el.attr('href'),
        replace = 'www.bing.com',
        regex = /www.+.com\//,
        replacement = hash.replace(regex, replace);

    $el.attr('href', replacement);

});

答案 2 :(得分:0)

缩短

$('a').prop('href', function(i,e){ return e.replace('google', 'bing')});