簡體   English   中英

獲取href onclick並通過鏈接重定向

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM