What about the case where the links are being generated while the page is being used? This occurs frequently with today's more complex front end frameworks.
The proper solution would probably be to put the click event listener on the document. This is because events on elements propagate to their parents and because a link is actually acted upon by the top-most parent.
This will work for all links, whether they are loaded with the page, or generated dynamically on the front end at any point in time.
function interceptClickEvent(e) {
var href;
var target = e.target || e.srcElement;
if (target.tagName === 'A') {
href = target.getAttribute('href');
//put your logic here...
if (true) {
//tell the browser not to respond to the link click
e.preventDefault();
}
}
}
//listen for link click events at the document level
if (document.addEventListener) {
document.addEventListener('click', interceptClickEvent);
} else if (document.attachEvent) {
document.attachEvent('onclick', interceptClickEvent);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…