简体   繁体   中英

Call a jQuery function once

I'm trying to make a class method in JS where an action have to be repeated only once. The method is call in a loop, and I want it method to move a character once and stop. But the click event is repeated a lot, so the character move ~40 times, and when I try with the jQuery "one()" it doesn't works, it's the same.

So that is my function (called in a permanent loop) :

Player.prototype.pushBox = function() {

    $(".box").click(function() { // The 'one()' doesn't resolve anything

        console.log('coucou'); // This is printing 40 times 

        for (var i = 0; i < boxArray.length; i++) {
            var box = boxArray[i];

            if (box.id == player.id + moveHorizontal) {
                $("#tile" + box.id).addClass('ground');
                box.x += boxSize;
                box.id += moveHorizontal;
                player.x += boxSize; // So this is called 40 times 
                player.id += moveHorizontal;
            }
        }
    });
 }

Maybe you have 40 objects with class "box" and the click event is triggered 40 times even if you use one()

  $(".box").one('click', function() { console.log('sss'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"><div class="box"><div class="box">click</div></div></div> 

http://jsfiddle.net/g39dkn2t/1/

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