问题
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