【问题标题】:Replace URLs with string by class or element按类或元素用字符串替换 URL
【发布时间】:2015-05-15 18:16:39
【问题描述】:

新手提醒。

我正在尝试用字符串“网站”替换当前显示在页面上的 URL。它不能是所有 URL,必须是特定于类的。此外,每个 URL 都不同,但它们的结构 (DOM) 相同。我可以 GetElementByID 或选择单个元素吗?

如何使用 JS 来解决这个问题?非常感谢您提出的任何建议!

我的开始:

<script type="text/javascript">

$(document).ready(function() {

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

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

    });
});

【问题讨论】:

  • 请添加您的 HTML 代码
  • 如果您展示一个 HTML 样本,包括一个应该更改的 URL 和一个不应更改的 URL,将会很有帮助。
  • 网站:uofmhealth.org/medical-services/abnormal- heart-rhythms" title="www.uofmhealth.org/medical-services/abnormal-heart-rhythms" target="_blank">www.uofmhealth.org/medical-services/abnormal-heart-韵律跨度>

标签: javascript jquery str-replace


【解决方案1】:

您可以更改目标的主机。

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

这将使结构保持不变。 “www.host.com/sub1/index.php”会变成“www.newhost.com/sub1/index.php”

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

【讨论】:

  • 几秒钟前通过检查 dom 中的元素找到了它,:D
【解决方案2】:

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

// 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!");
<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>

【讨论】:

    【解决方案3】:

    假设您使用 replace-url 类创建链接

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

    这个 js 可以工作

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

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签