简体   繁体   中英

How make javascript function work only one time

How to make Javascript function work only one time ?

    if (window.location.hash) {
        $(document).ready(function () {
        var id = window.location.hash;
        $(id).trigger('click');
    });
        $('li').click(function () {
            $(this).prependTo($(this).parent());
        });
    }

I need auto-click on that li element which link user comes to website. web.com/#2 (list order - 2 1 3 4 5) , web.com/#4 (list order - 4 1 2 3). but i want than user stay in website with hash url list elements stay in their places then user click for example on 3 list element he must stay and his place so list order (4 1 2 3). I just need change list order by url hash on load page.

I solved it

     if (window.location.hash) {

            $('li').one('click',function () {
                if (!window.run){
            $(this).prependTo($(this).parent());
                    window.run = true;
                }
        });
        $(document).ready(function () {
            var id = window.location.hash;
            $(id).trigger('click');
        });
    }

In your particular case the simplest solution is to use .one() , which unbinds the handler after running it the first time:

$('li').one('click',function () { ... }

Another approach is to have the function redefine itself to a no-op after it runs. This can be useful in some cases when there isn't a convenient event handler to unbind:

var oneTimeFunction = function() {
  console.log("This will only happen once.");
  oneTimeFunction = function() {};
}

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