简体   繁体   English

如何在单击时将 function 中的变量作为全局变量返回

[英]How to return a variable from a function as a global variable on click

I would like to return "a=5" variable from the function on click as a global variable and then alert it.我想在单击时从 function 返回“a=5”变量作为全局变量,然后对其发出警报。 Can you please only reply with javascript codes and not jquery.您能否只回复 javascript 代码而不是 jquery。 I am trying to understand javascript.我想了解 javascript。

 function startBtn() { var a = 5; return a; } document.getElementsByName("submit-button")[0].addEventListener("click", startBtn); // var test = startBtn(); //Does not work as I want. I want to pass this as a global variable. // alert(test); //Does not work as I want
 <input class="submit-btn" type="submit" name="submit-button" value="Start">

Thanks.谢谢。

Get the value of the function when the user click on the button and alert inside clickListener .当用户click按钮并在clickListener中发出alert时,获取 function 的值。

As per your code snippet you are getting the value of the startBtn function outside of the click listener and alerting it also give 5 , but you need to get the value and alert that value only after the user click on the button not when JS is compiled.根据您的代码片段,您将在点击侦听器之外获取startBtn function 的值并alerting它也给出5 ,但您需要获取该值并仅在用户单击按钮后而不是在编译 JS 时警告该值.

 function startBtn() { var a = 5; return a; } document.getElementsByName("submit-button")[0].addEventListener("click", () => { var test = startBtn(); alert(test); }); var test = startBtn(); alert(test);
 <input class="submit-btn" type="submit" name="submit-button" value="Start">

if you want to alert a from js function just insert the alert function on your startBtn function like this如果你想从 js function 发出警报,只需像这样在 startBtn function 上插入警报 function

 function startBtn() { var a = 5; alert(a); } document.getElementsByName("submit-button")[0].addEventListener("click", startBtn); // var test = startBtn(); //Does not work as I want // alert(test); //Does not work as I want
 <input class="submit-btn" type="submit" name="submit-button" value="Start">

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

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