I'm working on a project where I have to find all links on page and attach an event to them.
Problem is, I have to exclude all non-navigating links.
e.g.
the following scenarios should be excluded
<a>
<a href="">
<a href="#">
<a href="#" onclick="return false;" />
<a href="javascript:void(0)">
<a href="javascript:{}">
<a href="#0">
The following code gets all the links and attaches event to it. But it does not exclude the above scenarios.
var links = document.getElementsByTagName('a');
for (let link of links) {
if (link.href == base || (link.href.indexOf(base + '#') >= 0)) {
console.log(' - link[' + link.href + '] is same');
} else {
console.log(' + link[' + link.href + '] is bindable');
link.addEventListener("click", function (e) {
fireEvent();
});
}
}
From my research, the closest I seem to get to achieving this is through a regular expression like:
var expression = /[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}([-a-zA-Z0-9()@:%_+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = link.getAttribute("href");
if (t.match(regex)) {
alert("Successful match");
} else {
alert("No match");
}
But I'm looking for a better method or an optimal solution for this. Please can you help me out.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…