获取 href onclick 并使用链接重定向 [英] get href onclick and redirect with link
问题描述
我正在尝试使用以下代码从一个页面重定向到另一个页面,并使用特定的a"标签点击并附加在 clk 变量中的特定链接
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
例如假设当我点击第一个链接(或者可能是其他链接)然后在那个特定的点击我得到该链接的 href 并存储在 clk 变量中,并且还重定向到具有该特定链接的其他页面.
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.
推荐答案
您不需要使用循环来添加 onclick
事件,因为您使用的是内联事件 onclick
,您也可以使用 getAttribute
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>
但是如果在你的项目中有 jQuery 你可以像这样解决这个问题
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>
注意 - id
必须唯一
这篇关于获取 href onclick 并使用链接重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!