简体   繁体   English

基本的Javascript问题(增加价值)

[英]Basic Javascript issue (adding value)

Here's my fiddle : 这是我的小提琴:

http://jsfiddle.net/JWww3/ http://jsfiddle.net/JWww3/

I'm not sure to understand why this code is not working. 我不确定要理解为什么此代码无法正常工作。

What I want to add +1 to the "ajout" variable when I click on the "+1" button. 当我单击“ +1”按钮时,我想将+1添加到“ ajout”变量中。 And if ajout = 5 (after 5 clicks)...then alert("Hello"); 如果ajout = 5(5次点击后)...则警报(“ Hello”);

Why am I doing wrong? 我为什么做错了?

Here's my code : 这是我的代码:

HTML : HTML:

<input type="button" onclick="clickit();" id="click1" value="+1"/>​

JS : JS:

var ajout = 0;
function clickit()
{
 ajout +=1;    
}

if (ajout==5)
{
alert("TEST");   
}

Thank you! 谢谢!

I think this is what you want: 我认为这是您想要的:

var ajout = 0;
function clickit()
{
    ajout += 1;

    if (ajout==5)
    {
        alert("TEST");   
    }   
}

I suppose it should be 我想应该是

ajout += 1;

And what you have is 而你拥有的是

=+

Select "no wrap (body)" option from jsfiddle. 从jsfiddle中选择“ no wrap(body)”选项。 Otherwise clickit function is defined only after DOM has loaded, which means it could never get executed. 否则,只有在加载DOM之后才定义clickit函数,这意味着它将永远无法执行。

Also make sure to put that alert inside clickit function to make sure it gets executed when you call that function. 另外,请确保将该alert放入clickit函数中,以确保在调用该函数时执行该alert

Try this : 尝试这个 :

var ajout = 0;
jQuery('#click1').click(function(){
    ajout += 1;    
    console.log(ajout);
    if (ajout==5)
    {
    alert("TEST");   
    }
});

Here is the Demo 这是演示

Try This: 尝试这个:

<input type="button" onclick="clickit();" id="click1" value="+1"/>
<script>
var ajout = 0;
function clickit()
{
 ajout += 1;    
    if (ajout==5)
    {
        alert("TEST");   
    }
}

</script>

In addition to what the other 2 have said, your evaluation code should be within the function, otherwise it is NOT going to be called every time the button is clicked, which I think is what you are after. 除了其他2所说的内容之外,您的评估代码应该在函数中,否则每次单击按钮时都不会调用它,我想这就是您想要的。

var ajout = 0;
function clickit()
{
 ajout++;  
 if (ajout==5)
   alert("TEST");   
}

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

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