event.preventDefault() on first click then remove

后端 未结 5 1438
余生分开走
余生分开走 2021-02-03 13:35

I have the default anchor disabled if it has a class subnav as shown in this fiddle.

I only want this disabled for the first click then I want the normal anchor function

相关标签:
5条回答
  • 2021-02-03 14:02

    this will work for you

    $("#elementid").bind("click", function( event ) {
      alert("This will be displayed only once.");
      event.preventDefault(); 
      $(this).unbind( event );
    });
    
    0 讨论(0)
  • 2021-02-03 14:09

    You can pass false to one():

    $(".subnav a").one("click", false);
    

    Passing false instead of a handler is equivalent to passing a handler that returns false, effectively stopping the event's propagation and preventing its default behavior.

    This is explained in the documentation for bind():

    In jQuery 1.4.3 you can now pass in false in place of an event handler. This will bind an event handler equivalent to: function() { return false; }.

    0 讨论(0)
  • 2021-02-03 14:16

    You could use something as simple as self unbind in the click handler.

    Something like

    function stopEventOnce(event) {
      event.preventDefault();
      $(this).unbind('click',stopEventOnce);
      return false;
    }
    $(".subnav a").bind('click', stopEventOnce);
    

    Modified fiddle

    0 讨论(0)
  • 2021-02-03 14:18

    Bind the event handler with one()docu. It executes once and automatically unbinds itself afterwards.

    $(".subnav a").one("click", function(event) {
      event.preventDefault();
    });
    

    Alternatively you can unbind it yourself directly in the function. It's good to use a namespace for that

    $(".subnav a").bind("click.myclick", function(event) {
      event.preventDefault();
      $(this).unbind(".myclick");
    });
    
    0 讨论(0)
  • 2021-02-03 14:19

    This works well. The second click goes to the page...

    $(".smallNavigation > ul > li > a").click(function (e) {
    
        $("ul.sub-menu").hide();
        $("ul.sub-menu", $(this).parent("li")).show();
    
        e.preventDefault();
        $(this).unbind(e);
    
    }
    
    0 讨论(0)
提交回复
热议问题