How to append the id of an anchor tag to a new href in jquery and replace the href attribute in a page?

问题: I have the following: <a id="sample"></a> I want to change this to: <a href="https://www.exampledomain/testpage.aspx#sample"></a> using ei...

问题:

I have the following:

<a id="sample"></a>

I want to change this to:

<a href="https://www.exampledomain/testpage.aspx#sample"></a>

using either jQuery or plain JavaScript. The "sample" is a non-unique, dynamic attribute, but the domain I need to 'pre-pend' to it is always the same value. Thank you in advance.


回答1:

Try .querySelectorAll() and .forEach(). This demo adds href, text, and title (shows full href value when user hovers over a link)

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>


回答2:

Here's a jQuery solution. If you don't need this for every single link, you should update the anchor variable to use a class or other selector.

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>


回答3:

You can set the href before and then removing the attribute 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>

回答4:

const a = $("a");
const id = a.attr("id")
const host = "https://www.exampledomain/testpage.aspx#" 

 a.attr("href", `${host}${id}`)
  • 发表于 2019-03-31 20:25
  • 阅读 ( 3761 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除