替换我的<a> links using jquery

时间:2018-10-22 10:13:41

标签: javascript 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?

2 个答案:

答案 0 :(得分:1)

设置target="_blank"的方式就差不多了,就像更新href一样

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

例如

$("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>

答案 1 :(得分:0)

以下是供您参考的基本示例:

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);

请注意,您可能需要根据实际情况调整split部分,例如,如果您有多个参数,则需要在&处进行拆分