开发者

How do I know if a button was already clicked?

开发者 https://www.devze.com 2023-02-01 13:31 出处:网络
In JavaScript, when a user clicks a button, how do I know if it\'s the same button that he clicked the last time?

In JavaScript, when a user clicks a button, how do I know if it's the same button that he clicked the last time? For example, if a user clicks a "play" button, and a stop button a few seconds after, how can I know that he clicked the play button befo开发者_C百科re the stop button?


If you use jquery library for the javascript you can use toggle event :

In the html code

<input type="button" id="mybutton">

And in the javascript

$('#mybutton').toggle(function() {
    //here play function
}, function() {
    //here stop function
});

And you can add and remove css to the button so it can appear as a play or stop one.


var lastButton;

<input type="button" onclick="function(lastButton = this){}" />


Maintain a global reference to the button that was clicked in click event handler of appropriate button and compare it in subsequent runs. Sample Code:

<script type="text/javascript">
    var prevButton = null;
    .
    .
    .
    .
    function play(el)
    {
        if(el == prevButton) //Check if User has clicked the same button
        {
            //Add your code here
        }
        else
        {
        }
        prevButton = el;
    }

    .
    .
    .
    function stop(el)
    {
        if(el == prevButton) //Check if User has clicked the same button
        {
            //Add your code here    
        }
        else
        {
        }
        prevButton = el;
    }
    .
    .
    .
</script>
<input type="button" value="Play" onClick="play(this)"/>
<input type="button" value="Stop" onClick="stop(this)"/>


Have a global variable name playClicked, and set it to true when the Play button is clicked. You can then check this in the event handler for the Stop button click event.


I suppose you could save the button last pressed into a variable. Or you could have some kind of state (playing, stopped, paused, fast-forwarding, etc.) and buttons can behave differently based on the state.


Place an onclick event on the play button that sets a global flag which you can check when the user clicks on the stop button.


You could create an array, and, on the function that handles a click on the button, you could append the id of the button clicked to the array.

To get the button clicked before, you would simply access the second to last item in the array.

0

精彩评论

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