简体   繁体   中英

trying to attach a click event to an id that only fires once

UPDATE turns out the code is actually working see my answer below

I'm having some troubles here. I thought I found my answer in the .one method, but apparently, .one means ONLY ONCE PER PAGE PER ANYTHING EVER which isn't exactly what I was going for. Here's what my intention was:

$("#someID").one('mouseover', function() {

//do some stuff

});

$("#someOtherID").one('mouseover', function() {

//do some stuff

});

My expectation was that once that first one fired, that mouseover event would no longer fire for THAT ELEMENT.

The problem with this is that once the first one fires, the second one will not fire either. So the .one method appears to be disabling ALL mouseover events for ALL elements after that first one fires.

I did not expect this, I expected the .one to only apply to that first element. Is this just a flaw in my understanding of the .one method or am I coding wrong?

If it's just a flaw in my understanding, could someone point me in the right direction to correct my code?

Thank you in advance!

This is embarassing, I hope I don't get dinged for this and blocked again from stackoverflow (the easiest thing ever to get blocked from and the hardest to get unblocked).

First, @CertainPerformance, thanks for taking the time to look at my question. My real code didn't have the two mistakes you mentioned, I updated my post to reflect the correct syntax.

I'll be honest, my code is working now, and I have no idea why. I suspect I've been dealing with some crazy caching issues which frustrates me because I'm using inMotionHosting which has really great reviews, and I have caching disabled in cPanel.

If anything, maybe this thread will benefit somebody searching "how to make event fire only once in javascript".

You could make the callback run once like this:

    // Extend the function prototype
    Function.prototype.once = function() {

        // Variables
        var func = this, // Current function
            result;

        // Returns the function
        return function() {

            // If function is set
            if(func) {

                // Executes the function
                result = func.apply(this, arguments);

                // Unset the function, so it will not be called again
                func = null;

            }

            // (:
            return result;

        };

    };

    // Bind the event to the function you will use as a callback
    $("#someID").on('mouseover', function() {

       console.log('just once');

    }.once());

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