简体   繁体   English

Javascript检查事件是否已被触发或单击

[英]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. 改用.one绑定。 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;
    }
    }

  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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