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

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

I have links like this:

click
c         


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

    Without any JS library or jQuery. To open a nice popup window if possible. Fails safely to normal link open.

    <a href="https://acme.com/" onclick="onclick="openNewWindow(event, this.href);">...</a>
    

    And the helper function:

    function openNewWindow(event, location) {
      if (event.preventDefault && event.stopImmediatePropagation) { 
        event.preventDefault(); 
        event.stopImmediatePropagation(); 
      } else {
        event.returnValue = false; 
      }
      window.open(location, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=450');
    }
    
    0 讨论(0)
  • 2020-11-28 04:26

    You can access the event from onclick like this:

    <button onclick="yourFunc(event);">go</button>
    

    and at your javascript function, my advice is adding that first line statement as:

    function yourFunc(e) {
        e = e ? e : event;
    }
    

    then use everywhere e as event variable

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

    Can you not just remove the href attribute from the a tag?

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

    I think when we use onClick we want to do something different than default. So, for all your links with onClick:

    $("a[onClick]").on("click", function(e) {
      return e.preventDefault();
    });
    
    0 讨论(0)
  • 2020-11-28 04:39
    <script type="text/javascript">
    $('a').click(function(){
       return false;
    });
    <script>
    
    0 讨论(0)
提交回复
热议问题