javascript - js 阻止href 并获取href 的值怎么写
黄舟
黄舟 2017-04-10 12:44:22
0
2
784
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 <html xmlns="http://www.w3.org/1999/xhtml"> 
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
 <title>JS阻止链接跳转</title> 
 <script type="text/javascript">  
 function stopDefault( e ) 
 {       
 if ( e && e.preventDefault )          
     e.preventDefault();      
 else          
 
 window.event.returnValue = false;              
 return false;  }  
 
 </script>  
 </head> 
 <body> 
<a href="http://www.baidu.com">百度</a>  
<a href="http://www.google.com">google</a>  
 <script type="text/javascript">  
 var test = document.getElementsByTagName('a');
 
  for (var i=0; i<test.length; i++ ) { 
	test[i].onclick = function(e) {  
		alert(test[i].href);   
		stopDefault(e); 
	} 
} 
 </script> 
 </body> 
 </html>

我是这么写的,没有用。。
我想实现的是js 阻止href 跳转并获取href 的值alert 出来怎么写(不用jquery实现,不修改html,只用js)

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回覆(2)
刘奇
test[i].onclick = function(e) {
alert(test[i].href);
stopDefault(e);
}

修改为下面的代码,<title>下面的不要:

test[i].onclick = function(e) {
e.preventDefault(e);
alert(this.href);
}
PHPzhong

在chrome下测试通过:

<!DOCTYPE HTML>
<html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    
    <body>
        <a href="http://www.baidu.com">百度</a>
        <a href="http://www.google.com">google</a>
        <script type="text/javascript">
            var
             links = document.querySelectorAll('a')

             Array.prototype.forEach.call(links, function (link) {
                link.addEventListener('click', function (evt) {
                    evt.preventDefault()
                    alert(this.href)
                })
            })
        </script>
    </body>

</html>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板