简体   繁体   中英

How do you click on an HTML element without triggering onclick in js?

I'm using Google Analytics on my site. Since it's hand-made HTML, and it was already big when I installed it, I don't have it on all of my pages. The site is so big it doesn't make sense to do any page-by-page work.
I've written some code to prevent the default click action (so GA can fire), log the GA event, and then click on it again. I've been using this code to do that:

function trackClick(event) {
  event.preventDefault();
  console.log("clicked_on_"+String(this.myelem.href || this.myelem.onclick)+"_from_"+window.location.href);
  setTimeout(function(elemmy){
    elemmy.click();
  }, 300, this.myelem);
  gtag("event", "clicked_on_"+String(this.myelem.href || this.myelem.onclick)+"_from_"+window.location.href);
}
var atags = document.getElementsByTagName("a");
for (var i = 0; i < atags.length; i++) {
  atags[i].addEventListener("click", trackClick.bind({myelem: atags[i]}));
}

The problem was, as soon as I clicked on it, it triggered an infinite loop. How do you trigger a click with JS, without triggering a specific event handler?

If all your eventListeners are hand coded and easily accessible I believe you could have them listen for a different event. So you could switch these from listening for a click event and have your custom function fire off a different event like.

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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