简体   繁体   中英

Javascript check to see if an event has already been fired or clicked

I have a function that needs to fire when I click on a chevron tab. However I only need that function to fire that first time we load the page. How can I prevent it form firing every time the tab is clicked?

    $('#navi a').bind('click',function(e){
        var $this   = $(this);
        var prevButton  = current;
        $this.closest('ul').find('li').removeClass('selected');

        if ( $(this).attr('id') == 'tab2')
        {
            //fire function only once
        }

    });

In case you need only part of your event handler to run once :

$("div").on("click",function(){
    if (!$(this).data("fired")) {
        console.log("Running once");
        $(this).data("fired",true);
    }

    console.log("Things as usual");
});

Demo

Use the .one binding instead. This will attach it to fire on the first click and remove itself.

Use:

var isalreadyclicked=false;
  $('#navi a').bind('click',function(e){
    var $this   = $(this);
    var prevButton  = current;
    $this.closest('ul').find('li').removeClass('selected');

    if ( $(this).attr('id') == 'tab2')
    {
    if(!isalreadyclicked){
        //fire function only once
    isalreadyclicked=true;
    }
    }

  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM