Hyperlink click is not firing

大城市里の小女人 提交于 2019-12-14 03:59:59

问题


I'd like to catch click on hyperlink with JavaScript. I used this code :

for (var i = 0; i < document.links.length; i++) { 
    document.links[i].onclick = function() { 
           doSomething();       
        } 
    }

On normal hyperlink <a href="index.html">Home</a> everything works but on link to pdf file

<a href="tmp.pdf">tmp.pdf</a>

action doSomething(); is not called. My page is redirected to tmp.pdf without firing click event. I don't have a idea why.

Can you advise me what is problem. I'd like to avoid jQuery.


回答1:


You could remove the href attribute and do the redirect to the file in the catch function. Do some logic and then redirect the user to the new page/file.

<a id="pdf" href="">tmp.pdf</a>

for (var i = 0; i < document.links.length; i++) { 
    document.links[i].onclick = function() { 
           doSomething();  
           if(link[s].id == "pdf"){
               window.location="tmp.pdf";
           }
        } 
    }



回答2:


I think you need to make sure, you're javascript executing after page load. it may works for you

$( document ).ready(function() {
 for (var i = 0; i < document.links.length; i++) {
  document.links[i].onclick = function() {
         alert('testing')
      }
  }
});

FYI, i'm using jQuery ready event to make sure script executes after page load.




回答3:


so, i found it...somewhere in javascript files i found this code that causes my problem

  if ( (String($(this).prop('href')).indexOf('.pdf') != -1)) {
    evt.stopPropagation();
    evt.cancelBubble = true;

thanks



来源:https://stackoverflow.com/questions/28886198/hyperlink-click-is-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!