How to disable the default behavior of the <a> attribute "href"?
I have a simple sidebar:
<div class="sidebar">
<ul class="nav">
<li class="Page1"><a href="Page1.html">Page1</a></li>
<li class="Page2"><a href="Page2.html">Page2</a></li>
<li class="Page3"><a href="Page3.html">Page3</a></li>
</ul>
</div>
This code exists on each of the pages: page1.html, page2.html, page3.html.
On page1.html, I would like the page not to be viewable.
On the page. Html, I would like page2 not to be clickable.
On the Pagehtml page, I would like the page not to be viewable.
Is it possible to do this without Javascript, i.e. pure HTML and CSS? If not, what would be the easiest way to do this using javascript, jQuery?
+1
4 answers
PHP , /.
: . - - , , .
, JavaScript, jQuery.
-, :
navlinks = document.querySelectorAll('nav a');
NodeList Array. :
function array(a) {
var r = []; for (var i = 0; i < a.length; i++)
r.push(a[i]);
return r;
}
navlinks = array(navlinks);
... forEach , :
navlinks.forEach(function(node) {
if (node.href == location)
node.addEventListener('click', function(e) { e.preventDefault(); }, false);
});
+4
The best way to do this would be server side. In pseudo code that will look something like this.
links = [
"Page1" : "page1.html"
"Page2" : "page2.html"
"Page3" : "page3.html"
]
html = ""
for linkTitle, linkUrl of links
if current_url is linkUrl
html += "<li>#{linkTitle}</li>"
else
html += "<li><a href='#{linkUrl}'>#{linkTitle}</a></li>"
return "<ul>" + html + "</ul>"
0