[英]get href onclick and redirect with link
我正在尝试执行以下代码,以单击特定的“ 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/>
上面的代码无法正常运行
例如,假设当我单击第一个链接(或可能是其他链接)时,然后在该特定单击上,我获得该链接的href并存储在clk变量中,并且还重定向到具有该特定链接的其他页面。
您不需要使用循环来添加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>
但是,如果您的项目中有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>
注意 id
必须是唯一的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.