简体   繁体   中英

How to run a function if a button is not clicked?

$("#RunCode").click(function(){
    var $this = $(this);
    if($this.data('clicked')) {
        console.log("Is clicked");
        $(".documentWrite").text("Is clicked");
    } else {
        $this.data('clicked', true);
        console.log("Is not clicked");
        $(".documentWrite").text("Is NOT clicked");
    }
});

jsFiddle

When I click on button I get "Is NOT clicked" , if I click again I get "Is clicked" .
Why do I get the code of unclick when the button is clicked?

Quote OP:

"Why do I get the code of unclick when the button is clicked?"

Because your conditional logic is flawed.

$("#RunCode").click(function(){
    var $this = $(this);
    if($this.data('clicked')) { //<- FAILS on first click. 'data' is not yet set.
        console.log("Is clicked");
        $(".documentWrite").text("Is clicked");
    } else {
        $this.data('clicked', true);
        console.log("Is not clicked");
        $(".documentWrite").text("Is NOT clicked");
    }
});

The data called 'clicked' is not true on the first click; you are only setting it true on first click.


Quote OP:

"How to run a function if a button is not clicked?"

What does this even mean? The code you've presented to us is entirely contained within a click event handler function. In other words, the function depends solely on the click event actually occurring. (It can never run without a click)

If you don't want to run the function on a click, then how?

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