Jquery if its the first time element is being clic

2020-06-17 05:34发布

问题:

I need my script to do something on the first time an element is clicked and continue to do something different on click 2,3,4 and so on

$('selector').click(function() {  
//I would realy like this variable to be updated  
var click = 0;  
    if (click === 0) {  
        do this  
        var click = 1;  
    } else {  
        do this  
    }
});//end click

really I think it should rely on the variables but I can't think of how to update the variable from here on out any help would be awesome.

回答1:

Have a look at jQuery's .data() method. Consider your example:

$('selector').click(function() {
    var $this = $(this),
        clickNum = $this.data('clickNum');

    if (!clickNum) clickNum = 1;

    alert(clickNum);

    $this.data('clickNum', ++clickNum);
});

See a working example here: http://jsfiddle.net/uaaft/



回答2:

Use data to persist your state with the element.

In your click handler,

use

$(this).data('number_of_clicks')

to retrieve the value and

$(this).data('number_of_clicks',some_value)

to set it.

Note: $(this).data('number_of_clicks') will return false if it hasn't been set yet

Edit: fixed link



回答3:

Another alternative might be to have two functions, and bind one using the one function in $(document).ready() (or wherever you are binding your handlers), and in that function, bind the second function to be run for all subsequent clicks using bind or click.

e.g.

function FirstTime(element) {
   // do stuff the first time round here
   $(element.target).click(AllOtherTimes);
}

function AllOtherTimes(element) {
   // do stuff all subsequent times here
}

$(function() {
    $('selector').one('click', FirstTime);
});


回答4:

This is super easy in vanilla Js. This is using proper, different click handlers

const onNextTimes = function(e) {
    // Do this after all but first click
};

node.addEventListener("click", function onFirstTime(e) {
    node.addEventListener("click", onNextTimes);
}, {once : true});

Documentation, CanIUse



回答5:

If you just need sequences of fixed behaviors, you can do this:

$('selector').toggle(function(){...}, function(){...}, function(){...},...);

Event handlers in the toggle method will be called orderly.



回答6:

$('#foo').one('click', function() { alert('This will be displayed only once.'); });

this would bind click event to Corresponding Html element once and unbind it automatically after first event rendering.

Or alternatively u could the following:

$("#foo").bind('click',function(){

// Some activity

$("#foo").unbind("click"); // bind it to some other event handler.

});