![](/img/trans.png)
[英]Jquery to modify all anchor tag href on a page and extract key request parameters from href attribute
[英]How to append the id of an anchor tag to a new href in jquery and replace the href attribute in a page?
我有以下几点:
<a id="sample"></a>
我想将其更改为:
<a href="https://www.exampledomain/testpage.aspx#sample"></a>
使用 jQuery 或纯 JavaScript。 “样本”是一个非唯一的动态属性,但我需要“预挂”到它的域始终是相同的值。 先感谢您。
尝试.querySelectorAll()
和.forEach()
。 此演示添加了href
、文本和title
(当用户将鼠标悬停在链接上时显示完整的href
值)
var linx = document.querySelectorAll('a'); linx.forEach(lnk => { let ID = lnk.id; const host = 'https://example.com/#'; lnk.href = host + ID; lnk.title = host + ID; lnk.textContent = ID; });
a { display: block }
<a id="ID0"></a> <a id="ID1"></a> <a id="ID2"></a> <a id="ID3"></a> <a id="ID4"></a> <a id="ID5"></a> <a id="ID6"></a> <a id="ID7"></a> <a id="ID8"></a> <a id="ID9"></a> <a id="IDA"></a> <a id="IDB"></a> <a id="IDC"></a> <a id="IDD"></a> <a id="IDE"></a> <a id="IDF"></a>
您可以先设置href,然后删除属性id
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="sample">Sample</a>
<a id="xxx">Sample xxx</a>
<script>
$(document).ready(function() {
function changeId(id){
console.log(id);
var a = document.getElementById(id);
a.href = "https://www.exampledomain/testpage.aspx#"+id;
$('#'+id).removeAttr('id');
};
changeId("sample");
changeId("xxx");
});
</script>
</body>
</html>
这是一个 jQuery 解决方案。 如果您不需要为每个链接都这样做,您应该更新锚变量以使用类或其他选择器。
var anchor = $("a"); var anchorTarget = "#" + anchor.attr("id"); var link = "https://www.exampledomain/testpage.aspx"; anchor.attr("href", link + anchorTarget);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <a id="sample">Test</a>
const a = $("a");
const id = a.attr("id")
const host = "https://www.exampledomain/testpage.aspx#"
a.attr("href", `${host}${id}`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.