Jquery if its the first time element is being clic

2020-06-17 05:42发布

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.

6条回答
该账号已被封号
2楼-- · 2020-06-17 06:01

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楼-- · 2020-06-17 06:03

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/

查看更多
爷的心禁止访问
4楼-- · 2020-06-17 06:09

$('#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.

});

查看更多
我命由我不由天
5楼-- · 2020-06-17 06:15

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);
});
查看更多
Melony?
6楼-- · 2020-06-17 06:15

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.

查看更多
Melony?
7楼-- · 2020-06-17 06:20

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

查看更多
登录 后发表回答