简体   繁体   English

按钮增加值不会显示该值?

[英]Button to increment value won't show the value?

I am trying to create a very basic JavaScript function that will increment a variable by 1 whenever it is clicked, and the variable will be displayed on the same page and show any updated value. 我正在尝试创建一个非常基本的JavaScript函数,该函数将在每次单击变量时将其增加1,并且该变量将显示在同一页面上并显示任何更新的值。 I can't seem to get the variable to write to the HTML document, what am I doing wrong? 我似乎无法获取要写入HTML文档的变量,我在做什么错? I assume the button works fine, but I don't think it is calling the function correctly: 我认为该按钮可以正常工作,但我认为它不能正确调用该函数:

function cookieClick(number) {
  cookies = cookies + number;
  document.getElementById("incrementValue").innerHTML = cookies;

} }

Here's the Fiddle: https://jsfiddle.net/6aj2zxb6/ 这是小提琴: https : //jsfiddle.net/6aj2zxb6/

Change the JavaScript setting Load type to No Wrap - in head in jsfiddle 将JSfiddle头部中的JavaScript设置``加载类型''更改为``无包装''

This is working fine

https://jsfiddle.net/6aj2zxb6/3/ https://jsfiddle.net/6aj2zxb6/3/

You problem was solved by fiddle settings, but if you are interested, try this: 小提琴设置解决了您的问题,但是如果您有兴趣,请尝试以下操作:

You can assign counter value into cookieClick property 您可以将计数器值分配给cookieClick属性

function cookieClick(number) {
    if(cookieClick.counter)cookieClick.counter=0;
    cookieClick.counter += number;
    document.getElementById("incrementValue").innerHTML = cookieClick.counter;
}

If you have var counter in the global (window) scope, it is more easy to overwrite it by another similar code. 如果您在全局(窗口)范围内具有var counter ,则更容易用另一个类似的代码覆盖它。 This is more safe solution. 这是更安全的解决方案。 You can use it as a cache in future;-) 您将来可以将其用作缓存;-)

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

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