How to disable default behaviour of “href” att

2019-08-15 02:34发布

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"><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 ?

4条回答
放我归山
2楼-- · 2019-08-15 03:04

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.

查看更多
不美不萌又怎样
3楼-- · 2019-08-15 03:08

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);
});
查看更多
Fickle 薄情
4楼-- · 2019-08-15 03:13

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>"
查看更多
Fickle 薄情
5楼-- · 2019-08-15 03:19

You could add

onclick="return false"

on the <a> tag that you want to disable.

查看更多
登录 后发表回答