用类或元素替换URL

时间:2015-05-15 18:16:39

标签: javascript jquery str-replace

新手提醒。

我正在尝试使用字符串" Website"替换当前在页面上显示的网址。它不是所有网址,必须是特定于类的。此外,URL各自不同,但它们的结构(DOM)相同。我可以GetElementByID还是选择一个单独的元素?

如何使用JS进行此操作?非常感谢任何和所有的建议!

我的开始:

<script type="text/javascript">

$(document).ready(function() {

    $(".element span").text(function(index, text) {

    return text.replace('http://dynamic url', 'Website');

    });
});

3 个答案:

答案 0 :(得分:0)

假设您使用课程replace-url

创建链接
<a href="http://someurl.com" class="replace-url">whatever</a>

这个js会起作用

$(document).ready(function() {

    $('a.replace-url').each(function() {
        this.href = 'website';
    });

});

答案 1 :(得分:0)

您可以更改目标的主机。

$(selector).prop('host', 'www.newhost.com');

这将保持结构相同。 &#34; www.host.com/sub1/index.php"将成为&#34; www.newhost.com/sub1/index.php"

示例:http://jsfiddle.net/7xt4gp4b/

答案 2 :(得分:0)

您可以选择具有特定类的所有<a>元素,然后更改href属性和html,如下所示(jQuery):

&#13;
&#13;
// select all of the links with the class "link"
var links = $('a[class="link"]');

// replace the link with a hash:
links.attr('href',"#");

// replace the text:
links.html("Hello World!");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="link" href="#foo">Foo</a>
<a class="link" href="#bar">Bar</a>
<a class="link" href="#baz">Baz</a>
&#13;
&#13;
&#13;