Access event to call preventdefault from custom function originating from onclick attribute of tag

前端 未结 11 2547
粉色の甜心
粉色の甜心 2020-11-28 04:07

I have links like this:

click
c         


        
相关标签:
11条回答
  • 2020-11-28 04:14

    e.preventDefault(); from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

    Or have return false from your method.

    0 讨论(0)
  • 2020-11-28 04:16

    I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).

    A quick example.

    function sayHi(e) {
       e.preventDefault();
       alert("hi");
    }
    <a href="http://google.co.uk" onclick="sayHi(event);">Click to say Hi</a>

    1. Run it as is and notice that the link does no redirect to Google after the alert.
    2. Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).
    0 讨论(0)
  • 2020-11-28 04:19

    Add a unique class to the links and a javascript that prevents default on links with this class:

    <a href="#" class="prevent-default" 
       onclick="$('.comment .hidden').toggle();">Show comments</a>
    
    <script>
      $(document).ready(function(){
    
        $("a.prevent-default").click(function(event) {
             event.preventDefault(); 
              });
      });
    </script>
    
    0 讨论(0)
  • 2020-11-28 04:20

    Simple!

    onclick="blabla(); return false"
    
    0 讨论(0)
  • 2020-11-28 04:21

    The simplest solution simply is:

    <a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>
    

    It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)

    <a onclick="
    if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
    window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' + 
    Math.round(new Date().getTime() / 1000);" 
    href="http://www.domain.com/docs/thingy.pdf">
    

    If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.

    0 讨论(0)
  • 2020-11-28 04:23

    Try this:

    <script>
        $("a").click(function(event) {
            event.preventDefault(); 
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题