[英]find and replace a unique html (href) string using javascript
使用Javascript,如何更改無類錨(假設定位到唯一的href字符串):
<a href="/unique-url-string/"></a>
為此,頁面加載:
<a href="/replacement-url-string/"></a>
您可以根據元素的href
屬性選擇元素。
$('a[href="/unique-url-string/"]').prop('href', '/replacement-url-string/');
如果您只想搜索這些網址的pathname
並保持域名不變,則可以嘗試以下操作:
$('a').filter(function() {
return this.pathname === "/foo/bar"
}).prop('href', function () {
this.pathname = '/butt/butt/butt';
return this;
});
嘗試這個:
$(function(){
$('a[href="/unique-url-string/"]').attr('href', '/replacement-url-string/');
});
替換部分:
$(function(){
var a = $('a[href="/unique-url-string/"]');
a.attr('href', a.attr('href').replace('unique', 'replacement'));
});
僅使用不帶庫的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;
}
}
}
只要這樣做:
$().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.