Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  2] [ 4]  / answers: 1 / hits: 26985  / 9 Years ago, thu, december 31, 2015, 12:00:00

I am trying to do below code for redirect from one page to other page with that particular 'a' tag click and appended with that particular link which is in clk variable





function abc()
{

var a = document.getElementsByTagName(a);
//alert(a);
for (var i = 0; i < a.length; i++) {
a[i].onclick = function (e) {
e.preventDefault();
var clk=$(this).attr('href');
window.location='http://www.shopeeon.com?ver='+clk;
//doSomething();
}
}
}

<a  id=first onclick='abc();' href=http://www.google.com >Google</a><br/>
<a id=second onclick='abc();' href=http://www.yahoo.com >Yahoo</a><br/>
<a id=third onclick='abc();' href=http://www.rediff.com >Rediff</a><br/>
<a id=third onclick='abc();' href=http://www.gmail.com >Gmail</a><br/>
<a id=third onclick='abc();' href=http://www.facebook.com >Facebook</a><br/>





The above code is not work properly that i want



e.g. suppose when i click on first link(or may be some other) then on that particular click i get href of that link and store in clk variable and also redirect to other page with that particular link.


More From » jquery

 Answers
5

You don't need use loop to add onclick event because you are using inline event onclick, also you can get href with method getAttribute





function abc(event) {
event.preventDefault();
var href = event.currentTarget.getAttribute('href')
window.location='http://www.shopeeon.com?ver=' + href;
}

<a id=first onclick='abc(event);' href=http://www.google.com >Google</a><br/>
<a id=second onclick='abc(event);' href=http://www.yahoo.com >Yahoo</a><br/>
<a id=third onclick='abc(event);' href=http://www.rediff.com >Rediff</a><br/>
<a id=fourth onclick='abc(event);' href=http://www.gmail.com >Gmail</a><br/>
<a id=fifth onclick='abc(event);' href=http://www.facebook.com >Facebook</a>





however if in your project there is jQuery you can solve this issue like this





$('a.redirect').click(function (event) {
event.preventDefault();
var href = $(this).attr('href')
window.location='http://www.shopeeon.com?ver=' + href;
});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<a class=redirect id=first href=http://www.google.com >Google</a><br/>
<a class=redirect id=second href=http://www.yahoo.com >Yahoo</a><br/>
<a class=redirect id=third href=http://www.rediff.com >Rediff</a><br/>
<a class=redirect id=fourth href=http://www.gmail.com >Gmail</a><br/>
<a class=redirect id=fifth href=http://www.facebook.com >Facebook</a>





Note - id must be unique


[#63885] Tuesday, December 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
admin

Total Points: 468
Total Questions: 103
Total Answers: 103

Location: Equatorial Guinea
Member since Sun, Feb 14, 2021
3 Years ago
;