繁体   English   中英

使用HTML和Javascript将所有HTML链接转换为另一个URL

[英]Convert all HTML Links to another URL with HTML and Javascript

我正在尝试在字符串的网站正文部分中获取所有HTML链接,并将它们替换为另一个链接。

尝试过类似的方法,但是没有用:

 var search = "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer"; var replacement = "https://example.com/"; document.body.innerHTML = document.body.innerHTML.split(search).join(replacement) 

其中“ https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer ”是我要替换的链接,而“ https://example.com/ ”是我要替换的链接。

这个怎么样:

$("[href='your link']").attr("href","new link");
$('body').find('a').each(function(){
    $(this).attr('href','your_new_link');
});

或不同的href:

$('body').find('a').each(function(){
    var ahref = $(this).attr('href');
    if ( ahref == 'your_old_link') {  /// or ahref.indexOf("your_old_link") >= 0
         $(this).attr('href','your_new_link_1');
    }else{
         $(this).attr('href','your_new_link_2');
    }

});

只需使用

  $("body a[href='https://www.cloudflare.com']").attr("href","https://example.com/");

这是根据您的问题使用纯JavaScript的解决方案

document.querySelectorAll("[href='" + search + "']").forEach(function(el){
    el.href = replacement );
});

如果您想使用jQuery,请按照Nir Tzezana的回答进行操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM