• Geek Answers Handbook

    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
    javascript jquery html css anchor
    Misha moroshko Jul 04 '10 at 11:13
    source share
    4 answers

    You can add

    onclick="return false"
    

    <a>, .

    +3
    Fabien Ménager 04 . '10 11:15

    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
    Delan Azabani 04 . '10 11:18

    HTML CSS, .

    , PHP, .

    +2
    phimuemue 04 . '10 11:17
    source share

    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
    fet Jun 12 '14 at 14:44
    source share

    More articles:

    • What is the most efficient way to get the source code of a webpage in C? - c
    • Conditionally execute a macro depending on the font used - latex
    • Automatic web tester for 404 links? - web-testing
    • Dynamic memory and constructor exceptions - c ++
    • Disable default link behavior - javascript
    • Windows: how to canonize a file in a special folder? - windows
    • Предотвращение виртуализации UAC? - uac
    • JQuery UI сортируется медленно в IE8, но работает хорошо в режиме IE7 и IE8 - jquery
    • What is an easy way to check if any process of a given identifier is running on Linux? - c ++
    • How to split an array? - arrays

    All Articles

    Geek Answers | 2019