Reputation: 151
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.
Upvotes: 3
Views: 28970
Reputation: 77482
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
Upvotes: 4