[英]How to change “href” attribute of link has specific “href” using jQuery?
If a pages has several links as such: 如果页面有多个链接:
<a href="http://www.domain.com/linka.html">Link A</a>
<a href="http://www.domain.com/linkb.html">Link B</a>
<a href="http://www.domain.com/linkc.html">Link C</a>
<a href="http://www.domain.com/linkd.html">Link D</a>
How do I change them all on page load to : 如何在页面加载时将它们全部更改为:
<a href="http://www.domain.com/folder/linka.html">Link A</a>
<a href="http://www.domain.com/folder/linkb.html">Link B</a>
<a href="http://www.domain.com/folder/linkc.html">Link C</a>
<a href="http://www.domain.com/folder/linkd.html">Link D</a>
You need to select all anchor tag that href
attribute of them start with "link" using [name^=”value”]
selector and end with ".html" using [name$=”value”]
selector. 您需要使用
[name^=”value”]
选择器选择所有href
属性的锚标记以“link”开头,并使用[name$=”value”]
选择器以“.html”结尾。 Then use .attr(function)
to iterate selected element and change href attribute of them in function. 然后使用
.attr(function)
迭代所选元素并在函数中更改它们的href属性。
$("a[href^='link'][href$='.html']").attr("href", function(i, attr){
return "folder/" + attr;
});
$("a[href^='link'][href$='.html']").attr("href", function(i, attr){ return "folder/" + attr; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="linka.html">Link A</a> <a href="linkb.html">Link B</a> <a href="linkc.html">Link C</a> <a href="linkd.html">Link D</a>
Also you can write the code in $(document).ready(function(){//code})
to running after page load. 您还可以将
$(document).ready(function(){//code})
为在页面加载后运行。
$.each($("a[href^='link'][href$='.html']"),function(){ $(this).attr("href",document.URL+"folder/"+$(this).attr("href")) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="linka.html">Link A</a> <a href="linkb.html">Link B</a> <a href="linkc.html">Link C</a> <a href="linkd.html">Link D</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.