繁体   English   中英

如何在 function 中使用全局变量,然后在另一个 function 中使用 output

[英]How to use Global Variable in a function and then use the output of the function in another function

我想初始化一个全局变量,然后在 function 中使用它来计算点击次数,然后在另一个 function 中使用计算出的for(i=0; i >= count; i++) 我在这里遇到的问题是,由于变量是全局变量,因此我无法在 submitForm() ZC1C425268E68385D1AB4ZZC17A94F 中使用 onClick function 的计算值。 变量“count”的值被重新分配为 0,因为它是全局的。

let count=0;

var add=document.querySelector('.fa-plus'); 
add.addEventListener('click', () =>{
       //Product Label
       count=count+1;
}

//to check if the variable has the computed result 
console.log(count);

function submitForm(e){
   for(i=0; i <= count; i++){
  const prod[i] = document.querySelector('#prod-'+i).value;
  ipcRenderer.send('item:add', item);                
   }
}
add.addEventListener('click', function(){
   //+= is just a shortcut. You can also use count++
   count+=1;
});

使用 var 而不是 let 可能会更好,因为尝试更改 let 通常会导致语法错误。

基于https://www.w3schools.com/jsref/met_element_addeventlistener.asp

(另外,除非你想让 for 循环循环 count+1,否则 i < count。记住 i 从 0 开始,而不是 1。)

暂无
暂无

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

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