问题描述:

I'm trying to write some JQuery so that whenever the user clicks on a link (i.e. the a tag), there's an alert, and the link does not actually jump to another place.

$(document).ready(function() {

$(document.body).on('click',"a",function(event){

event.preventDefault();

alert("Hello!");

});

});

The links in this file are not actually in the HTML code, but rather they are inserted by some other JavaScript. The alert works, but the default is not prevented. How can this be fixed?

网友答案:

Just to put an end to this question as troubleshooting happened in chat as it required too much back and forth...

Everyone was right, the code works perfectly. The problem OP had is that another code was adding an eventListener. This could not be tracked so only source file digging could make it appear. If the whole application uses jQuery, then jQuery knows all the events it has attached, so something similar to the troubleshooting proposed would show the events and then help to dig up the lines to add/remove: $._data( $("a")[0], "events" );

If, like the OP, you end up with codes you do not know that add vanilla (normal) JS events using addEventListener, there is no way to list the eventListeners of an element so debugging is not so easy. One small prototype hack can help you though, adding this code as the VERY FIRST js code to be executed by the page (just put it hard in a tag):

var sourceAEL = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(type, listener){
    console.log('Type: '+type);
    debug;//Will stop the code from executing allowing debugging in browser console (and thus know what calls it)
    sourceAEL.apply(this,[type,listener]);
};
相关阅读:
Top