简体   繁体   English

获取href onclick并通过链接重定向

[英]get href onclick and redirect with link

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 我正在尝试执行以下代码,以单击特定的“ a”标签从页面重定向到另一页面,并附加了位于clk变量中的特定链接

 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 上面的代码无法正常运行

eg 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. 例如,假设当我单击第一个链接(或可能是其他链接)时,然后在该特定单击上,我获得该链接的href并存储在clk变量中,并且还重定向到具有该特定链接的其他页面。

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 您不需要使用循环来添加onclick事件,因为您正在使用内联事件onclick ,也可以使用getAttribute方法获取href

 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 但是,如果您的项目中有jQuery,则可以像这样解决此问题

 $('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 注意 id 必须是唯一的

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

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