如何在 onClick 事件中增加计数器值?

How to increment counter value inside an onClick event?

我对 Google App Maker 和一般编程还很陌生,我正在制作一个应用程序,当单击“+”按钮(onClick 事件)时,会添加字段(有点像新的每次点击 table 行)。我正在尝试创建一个计数器来跟踪正在创建的 "rows" 数量。问题是,由于在 App Maker 中,所有代码显然都必须在 onClick 事件中进行,我无法设置全局变量,每次单击按钮时,计数器都会重新启动,因此始终为 1。

我尝试使用 localStorage,但我不知道如何让它工作,因为它仍然会始终保存相同的值。我该如何解决这个问题?

  var count = 0;
  count = count +1;
  localStorage.setItem('counter', JSON.stringify(parseFloat(count)));

  textArea.className = 'app-TextArea';
  textArea.style.margin = '8px';
  textArea.setAttribute("placeholder", "Follow up # " + localStorage.getItem('counter');

  widget.root.descendants.Panel1.getElement().appendChild(textArea);

您应该先从 localStorage 获取数据,然后递增它,最后将新值设置为 localStorage

var count = parseInt(localStorage('counter')) || 0; // Get value from localStorage 
count = count + 1;
localStorage.setItem('counter', count); // Set new value to localStorage

textArea.className = 'app-TextArea';
textArea.style.margin = '8px';
textArea.setAttribute("placeholder", "Follow up # " + count); // Use new value

widget.root.descendants.Panel1.getElement().appendChild(textArea);

您可以使用页面 custom properties.

所以在页面中,你可以添加一个Number自定义属性并命名为counter。 那么你的代码应该是这样的:

  var count = widget.root.properties.counter || 0;
  count += 1;
  widget.root.properties.counter = count;

  textArea.className = 'app-TextArea';
  textArea.style.margin = '8px';
  textArea.setAttribute("placeholder", "Follow up # " + count);

  widget.root.descendants.Panel1.getElement().appendChild(textArea);