简体   繁体   English

仅使用纯JavaScript修改所有链接的href属性

[英]Modify all links' href attribute using plain javascript only

I have an email template to send on a shipping notification that includes a shipping tracking number as below and I need to clear all the spaces from href using plain javascript: 我有一个电子邮件模板可以发送包含以下运输跟踪号的运输通知,并且我需要使用普通javascript清除href所有空格:

<a class="press-bt" id="clearSpace" href="https://www.royalmail.com/track-your-item?trackNumber=JX12 0008 990 90GB">TRACK</a>

I can get it right using jQuery but not using Javascript 我可以使用jQuery而不是使用Javascript正确处理

I am trying to do it this way: 我正在尝试这样做:

window.onload = function() {
    var str = document.getElementById("mylink");
    document.write( str.replaceAll("\\s+","") );
});

Working code using jQuery: 使用jQuery的工作代码:

$(document).ready(function() {
    $('a').attr('href', function (_, val) {
        return val.replace(/\s/g, '');
    });
});

You should, if possible, remove the spaces server-side. 如果可能,应该删除服务器端的空格。 I hope you understand no javascript will run in the emails you send. 我希望你明白没有的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, "");
  }
}

In modern browsers, you can replace the for loop with Array.prototype.forEach . 在现代浏览器中,可以将for循环替换为Array.prototype.forEach This method can be normally called on arrays ( [ ... ] ), but the list returned by getElementsByTagName is not an array, so use this trick: 通常可以在数组( [ ... ] )上调用此方法,但是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");
  });
}

Search for Function.prototype.call to learn more about calling functions on objects. 搜索Function.prototype.call以了解有关在对象上调用函数的更多信息。

Target the element by its id , grab the href attribute, and set it again by removing the spaces. 通过其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.

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