简体   繁体   English

使用javascript查找并替换唯一的html(href)字符串

[英]find and replace a unique html (href) string using javascript

Using Javascript, how can I change this classless anchor (assuming targeting unique href string): 使用Javascript,如何更改无类锚(假设定位到唯一的href字符串):

<a href="/unique-url-string/"></a>

to this, on page load: 为此,页面加载:

<a href="/replacement-url-string/"></a>

You can select the element based on its href prop. 您可以根据元素的href属性选择元素。

$('a[href="/unique-url-string/"]').prop('href', '/replacement-url-string/');

If you want to only search the pathname of these urls and keep the domain name the same you can try something like: 如果您只想搜索这些网址的pathname并保持域名不变,则可以尝试以下操作:

$('a').filter(function() {
  return this.pathname === "/foo/bar"
}).prop('href', function () {
  this.pathname = '/butt/butt/butt';
  return this;
});

Try this: 尝试这个:

$(function(){
   $('a[href="/unique-url-string/"]').attr('href', '/replacement-url-string/'); 
});

To replace a portion: 替换部分:

$(function(){
    var a = $('a[href="/unique-url-string/"]');
   a.attr('href', a.attr('href').replace('unique', 'replacement')); 
});

Using only JavaScript without library 仅使用不带库的JavaScript

function replaceLink(oldLink, newLink) {
var x = document.getElementsByTagName("a");
    for(var i = 0; i < x.length; i++)
        if(x[i].href == oldLink) {
            x[i].href == newLink; 
            break; 
        }
    }
}

Just do this : 只要这样做:

$().ready(function(){
    $('a').attr("href").replace("unique","replacement");
});

 var link = document.getElementById('linkToChange'); console.log(link.href); link.href = "http://www.google.com"; 
 <a href="about:blank" id="linkToChange">me</a> 

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

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