简体   繁体   English

将JS变量动态设置为点击锚点的href

[英]Set JS Variable to href of clicked anchor dynamically

I need to set a variable's value based on the href of a clicked link.我需要根据单击的链接的 href 设置变量的值。

I know that I can set the variable using an event listener that would run this when the link is clicked我知道我可以使用事件侦听器设置变量,该事件侦听器将在单击链接时运行

var x = document.getElementById("myAnchor").href

But that is set to a single element.但这被设置为单个元素。 I need it to work dynamically based on which link is clicked.我需要它根据点击的链接动态工作。 For example:例如:

<a href="/link1">Partner A</a>
<a href="/link2">Partner B</a>
<a href="/link3">Partner C</a> 
// function to attach click event to all links
function attachClickEvent() {
  var linklist = document.getElementsByTagName('a');
  var listLength = linklist.length;
  var i = 0;
  for (; i < listLength; i++) {
    linklist[i].addEventListener("click", ClickedLinkEvent);
  }
}

window.onload = attachClickEvent;

// function that creates click event
function ClickedLinkEvent() {
  var anchor = obj.href;
  console.log(anchor);
  if (anchor.includes('clientdomain')) {
    //do nothing
  } else {
    SendLinkEvent();
  }
}

// function to run on click event
function SendLinkEvent() {
  ga('send', {
    hitType: 'event',
    eventCategory: 'Affiliate Link',
    eventAction: 'Click',
    eventLabel: anchor
  });
}

The anchor variable needs to be set to /link1 if Partner A is clicked, but /link2 if Partner B is clicked.如果点击合作伙伴A,则锚变量需要设置为/link1,如果点击合作伙伴B,则需要设置为/link2。

So, is there a way to do this with vanilla JS?那么,有没有办法用香草 JS 做到这一点?

If you adjust the ClickedLinkEvent method declaration and add an argument to the method signature, then you will have the event object.如果您调整ClickedLinkEvent方法声明并向方法签名添加参数,那么您将拥有事件对象。 The event object has a target parameter.事件对象有一个目标参数。 If I understood you correctly, this is what you need.如果我理解正确的话,这就是你所需要的。 Don't you?不是吗?

function ClickedLinkEvent(e) {
    console.log('hello', e);
    var anchor = e.target.href;
    console.log(anchor);
    if (anchor.includes('clientdomain')){
       //do nothing
    }
    else {
         SendLinkEvent(anchor);
    }
}

You can set custom attributes to the a element like this:您可以像这样为 a 元素设置自定义属性:

<a href="..." id="myAnchor" data-partner="your_important_data_here">Link A</a>

Then in your js file:然后在你的 js 文件中:

var data_partner= document.getElementById('myAnchor').getAttribute('data-partner');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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