我正在尝试执行以下代码,使用特定的“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
,你也可以通过方法获取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
必须是唯一的
关于javascript - 获取 href onclick 并使用链接重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541560/