开发者

jQuery counting clicks, how to?

开发者 https://www.devze.com 2023-03-08 02:21 出处:网络
I want to make a function that on the first click does something an开发者_JAVA技巧d on the second one disables it, is there a method for it in jQuery?

I want to make a function that on the first click does something an开发者_JAVA技巧d on the second one disables it, is there a method for it in jQuery? Say for example, on the first click on the div it turns red, and on the second it goes back to the default white, and so on.

My thought was to make some even-odd counter, but there must be a better way..


You can use the toggle event.

Demo: http://jsfiddle.net/ThiefMaster/rHVdm/


In jQuery this is called toggle. With toggle, you can alternate between two different outcomes, like this:

<div id="click">Click me</div>

<script>
$("#click").toggle(function () {
  $(this).css("background-color", "red");
}, function () {
  $(this).css("background-color", "blue");
});
</script>

More information is available at the site of jQuery: http://api.jquery.com/toggle-event/


You can use a static variable (a variable that keeps it's value through all calls to the method). Your code can look like this:

function kill()
{
    if(!kill.staticVariable) kill.staticVariable = 0;

    if(staticVariable%2 == 0)
    {
        // do something
        staticVariable ++;
    }
    else
    {
        //do the other thing 
        staticVariable ++;
    }
}

This code would give you the functionality you want and it matches the way you thought about the problem, However this is not the best way to do it and I just wrote this because I'm sure that you'll find static variables very handy. Hope this helps :D

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号