2015-12-31 54 views
2

我试图做下面的重定向代码从一个网页到与特定的一个标签点击其他网页重定向,并与特定的链接,在CLK可变得到HREF的onclick与链接

function abc() 
 
{ 
 
\t 
 
var a = document.getElementsByTagName("a"); 
 
//alert(a); 
 
    for (var i = 0; i < a.length; i++) { 
 
     a[i].onclick = function (e) { 
 
     e.preventDefault(); 
 
\t \t var clk=$(this).attr('href'); 
 
\t \t 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变量中,并且还重定向到具有该特定链接的其他页面。

+0

你在你的代码中加入jQuery的? – gurvinder372

+0

是的,我加入了相同的页面 – shopeeon

+0

在这种情况下,你能分享一个小提琴吗? http://jsfiddle.net – gurvinder372

回答

3

你不需要使用循环,因为你正在使用内联事件onclick添加onclick事件,也可以得到与href方法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你可以这样解决这个问题

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

+1

以上两种都正常工作非常感谢您的宝贵支持 – shopeeon