[英]Modify all links' href attribute using plain javascript only
我有一個電子郵件模板可以發送包含以下運輸跟蹤號的運輸通知,並且我需要使用普通javascript清除href
所有空格:
<a class="press-bt" id="clearSpace" href="https://www.royalmail.com/track-your-item?trackNumber=JX12 0008 990 90GB">TRACK</a>
我可以使用jQuery而不是使用Javascript正確處理
我正在嘗試這樣做:
window.onload = function() {
var str = document.getElementById("mylink");
document.write( str.replaceAll("\\s+","") );
});
使用jQuery的工作代碼:
$(document).ready(function() {
$('a').attr('href', function (_, val) {
return val.replace(/\s/g, '');
});
});
如果可能,應該刪除服務器端的空格。 我希望你明白沒有的JavaScript將在您發送的電子郵件中運行。
// This prevents multiple `window.onload` conflict
window.addEventListener("load", clearLinks);
// This allows you to call the function even later if needed
function clearLinks() {
// Get list of all links in the page
var links = document.getElementsByTagName("a");
// Loop through links
for(var i=0,l=links.length; i<l; i++) {
// No need to use `getAttribute`, href is defined getter in all browsers
links[i].href = links[i].href.replace(/\s/g, "");
}
}
在現代瀏覽器中,可以將for循環替換為Array.prototype.forEach
。 通常可以在數組( [ ... ]
)上調用此方法,但是getElementsByTagName
返回的列表不是數組,因此請使用以下技巧:
function clearLinks() {
var links = document.getElementsByTagName("a");
// Loop through links
Array.prototype.forEach.call(links, function(link) {
link.href = link.href.replace(/[cC]/g, "c");
});
}
搜索Function.prototype.call
以了解有關在對象上調用函數的更多信息。
通過其id
定位元素,獲取href屬性,然后通過刪除空格再次進行設置。
var link = document.getElementById("mylink");
var href = link.getAttribute('href');
link.setAttribute('href', href.replace(/\s/g, ''));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.