简体   繁体   English

如果没有点击按钮,如何运行功能?

[英]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 的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? 单击按钮时为什么要获取unlick的代码?

Quote OP: 引用OP:

"Why do I get the code of unclick when the button is clicked?" “当点击按钮时,为什么我会得到unlick的代码?”

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; 第一次点击时,称为'clicked'datatrue ; you are only setting it true on first click. 您只需在第一次单击时设置true


Quote OP: 引用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. 您呈现给我们的代码完全包含在click事件处理函数中。 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? 如果您不想在单击时运行该功能,那么如何?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM