[英]Using JQuery to get anchor parameters from all links on page and replacing href of target link
[英]Replacing the href for my <a> links using jquery
我有以下 jQuery 代碼為我的所有鏈接添加'target', '_blank'
,如下所示:-
<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>
上面的代碼對我來說很完美。 但我想做額外的步驟,我需要替換所有<a>
鏈接的網址,如下所示:-
https://*****/Events/DispForm.aspx?ID=4
。 ID 將根據我正在查看的項目而有所不同。https://******/_layouts/15/Event.aspx?ListGuid=0579a0325489&ItemId=4
。 那么我如何從當前 url 獲取 Id 並為我所有相關的<a>
鏈接創建一個新的href
?
你快到了,你設置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>
下面是一個基本示例,供您用作指導:
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
部分,例如,如果您有多個參數,則需要在&
拆分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.