简体   繁体   中英

Replacing the href for my <a> links using jquery

I have the following jQuery code to add 'target', '_blank' for all my links, as follow:-

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script>

var pollCount = 0;
$(document).ready(function($){
   checkCalendar($);
});

function checkCalendar($) {
   //stop after 10 seconds
   if (pollCount > 20)
      return;
   //if the calendar hasn't loaded yet, then wait .5 seconds
   if ($('.ms-acal-title a').length < 1) {
      pollCount++;
      setTimeout(function(){checkCalendar($);}, 500);     
   }
   else {
      //the calendar has loaded, so do work
      $('.ms-acal-title a' ).attr('target', '_blank');
    }
}    
</script>

the above code is working perfectly for me. but i want to do additional step, where i need to replace the url for all the <a> links as follow:-

  1. currently the links will have a url as follow https://*****/Events/DispForm.aspx?ID=4 . where the ID will differ based on the item i am viewing.
  2. now i want the url to be as follow https://******/_layouts/15/Event.aspx?ListGuid=0579a0325489&ItemId=4 .

so how i can get the Id from the current url and create a new href for all my related <a> links?

You are almost there, the way you are setting the target="_blank" , the same way you can update the href something like

(this).attr("href", "newurlValue");

For example

 $("a").each(function() { $(this).attr('target', '_blank'); var id = $(this).attr("href").split("ID=")[1]; $(this).attr("href", `newurlValue/itemId=${id}`); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <a href="https://test.com/Events/DispForm.aspx?ID=4">Test4</a> <a href="https://test.com/Events/DispForm.aspx?ID=5">Test5</a>

Here's a basic example for you to use as guidance:

let oldurl = 'https://*****/Events/DispForm.aspx?ID=4';
let params = oldurl.split('=');
let newurl = 'https://******/_layouts/15/Event.aspx?ListGuid=0579a0325489&ID=' + params[1];
$('.ms-acal-title a' ).attr('href', newurl);

Just notice that you may need to adapt the split part to your use case, for example if you have multiple params you need to split at &

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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