suchen

Heim  >  Fragen und Antworten  >  Hauptteil

javascript - js 阻止href 并获取href 的值怎么写

<!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)

黄舟黄舟2894 Tage vor780

Antworte allen(2)Ich werde antworten

  • 怪我咯

    怪我咯2017-04-10 12:46:22

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

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

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

    Antwort
    0
  • PHPz

    PHPz2017-04-10 12:46:22

    在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>

    Antwort
    0
  • StornierenAntwort