so I have four links with different Href for example
<a href="markmendoza.com/123">
<a href="markmendoza.com/555">
<a href="markmendoza.com/666">
<a href="markmendoza.com/999">
and I wanted to manipulate the href when it got clicked by adding some more value
when it get click it will be:
markmendoza.com/123/?Sample
markmendoza.com/555/?Sample
markmendoza.com/666/?Sample
markmendoza.com/999/?Sample
I got here my code
let a = document.querySelectorAll('a');
for (let i = 0; i < a.length; i++) {
a[i].addEventListener("click", function(event) {
event.target.href = event.target.href + '/?Sample';
}
its adding fine but once you click it many times it just adds the /?Sample on the end of the link again and again so if I clicked the link 10x it will be markmendoza.com/123/?Sample?Sample?Sample?Sample?Sample?Sample?Sample
If you only want to add it once guard it's with an if statement like so:
for (let i = 0; i < a.length; i++) {
a[i].addEventListener("click", function (event) {
if (!event.target.href.includes('/?Sample')) { //add this
event.target.href = event.target.href + '/?Sample';
}
});
}
let links = document.querySelectorAll('a');
jQuery.each( links, function( a, val ) {
a.addEventListener("click", function(event) {
link_href = event.target.href || ''
if(!link_href.includes('/?Sample') {
event.target.href = link_href + '/?Sample';
}
}
});
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.