How to execute Jquery code only once??

后端 未结 9 2065
梦谈多话
梦谈多话 2020-12-16 15:52

I have one jquery method and i used call that method on click of a button . So in that code i have one line \" $(\"#loadingMessage\").css(\'padding-top\',\'6%\');

相关标签:
9条回答
  • 2020-12-16 16:19

    You can put a check around it that checks the padding-top. If it is not 6%, you need to set it. If it is, you skip the line. Tip: put the result of $('#loadingMessage') in a variable so you do not have to do a second element lookup.

    Like so (not tested):

    $('#SearchButton').click(function() {                 
        var $loadMsg = $("#loadingMessage");
    
        if($loadMsg.css('padding-top') !== '6%'){
             $loadMsg.css('padding-top', '6%');
        }
    });
    

    This is of course assuming that you want to execute the rest of the code in the click handler every time. Otherwise you can just unbind the click after the handler has been executed. Tip: use the jQuery on() and off() methods instead.

    0 讨论(0)
  • 2020-12-16 16:23

    you can use js closure to slove the question.

    function once(func) {
        let isExeced = false;
        return function(...arg) {
            if (isExeced) return void 0;
            isExeced = true;
            func.apply(null, arg)
        }
    }
    
    0 讨论(0)
  • 2020-12-16 16:27

    If you want to restrict #SearchButton click event to fire only once, use .one method

    $('#SearchButton').one('click', function() {
      ...
    });
    
    0 讨论(0)
  • 2020-12-16 16:28

    If you have to run only once a generic function without a particular event binding then use this.

    $(document).one('ready', function(){
       // your code
       $("#id").on("click", function() {
            // other code
       });
    });
    

    Useful if inside a function that is called many times (prevents onclick event from beein fired many times)

    0 讨论(0)
  • 2020-12-16 16:33

    Use a boolean as a global variable, like

    var flag = true;
    

    Now, set the condition before the execution, Like

    if(flag){  
       $("#loadingMessage").css('padding-top','6%');  
       flag=false;  
    }
    
    0 讨论(0)
  • 2020-12-16 16:35

    Use jQuery .one(). When using .one() method, the event handler function is only run once for each element.

    $('#SearchButton').one("click", function () {
        $("#loadingMessage").css('padding-top', '6%');
    });
    
    $('#SearchButton').click(function () {
        $(".spinner").css('visibility', 'hidden');
    
        loaderStart();
        document.getElementById('loadinggif3').style.display = "block";
        $("#loadinggif3").show();
        $(".col-sm-9").css('visibility', 'hidden');
        var str = $('#SearchText').val();
        str = str.trim();
        if (str == "") return false;
    });
    
    0 讨论(0)
提交回复
热议问题