I have a simple sidebar like this:
<div class="sidebar">
<ul class="nav">
<li class="Page1"><a href="Page1.html">Page1</a></li>
<li class="Page2">开发者_Python百科<a href="Page2.html">Page2</a></li>
<li class="Page3"><a href="Page3.html">Page3</a></li>
</ul>
</div>
This code exist on each one of the pages: page1.html, page2.html, page3.html.
On Page1.html, I would like Page1 not to be clickable.
On Page2.html, I would like Page2 not to be clickable. On Page3.html, I would like Page3 not to be clickable.Is that possible to do that without Javascript, i.e. pure HTML & CSS ? If not, what would be the easiest method to do that using Javascript, jQuery ?
You could add
onclick="return false"
on the <a>
tag that you want to disable.
I'd actually recommend PHP for this, as it avoids possible usability/accessibility problems.
Another note: I wouldn't bother doing this anyway. On my website, I keep all links available - the title tells the user where she is anyway, so disabling links only creates trouble.
No, you need JavaScript, but you don't need jQuery.
Firstly, select the elements:
navlinks = document.querySelectorAll('nav a');
You need to convert the NodeList
into an Array
. Use this function:
function array(a) {
var r = []; for (var i = 0; i < a.length; i++)
r.push(a[i]);
return r;
}
navlinks = array(navlinks);
Then... call forEach
and check for the right link, disabling it:
navlinks.forEach(function(node) {
if (node.href == location)
node.addEventListener('click', function(e) { e.preventDefault(); }, false);
});
If you want to do it purely with HTML and CSS, you have to generate a customized sidebar for each page.
However, if you dont mind using PHP, that shouldnt be much of a problem.
The best way to do it would be on the server side. In pseudocode that would 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>"
精彩评论