[英]How do I return a value from a function in JavaScript to a textbox in HTML
[英]How do I return a value from a function into a variable in javascript then display it using HTML?
我對 JS 很陌生,我已經為此苦苦掙扎了幾個小時。
<script> document.getElementById("myButton").onclick = function myFunction() { var Ra = document.getElementById("input1").value; var Rb = document.getElementById("input2").value; var Ea = (1) / ( (1) + (Math.pow((10), ((Rb - Ra) / (400)))) ); var Eap = Ea * 100; return Eap; } var result = myFunction(); </script> <div class="result"> Your probability of winning is: <script> document.write(result); </script> </div>
基本上,我從用戶那里獲取了兩個值,將其發送到 function 進行一些計算。 我想使用變量“Eap”的值以一種或另一種方式顯示計算結果。 我不能直接使用該變量,因為我假設它的 scope 僅在 function 內? 而且我無法存儲整個 function 的返回值。
只需使用.textContent
。
現在是 2022 年,我將.getElementById
更改為.querySelector
,將var
更改為const
。
document.querySelector('#button').addEventListener('click', () => { const Ra = document.querySelector('#input1').value; const Rb = document.querySelector('#input2').value; const Ea = (1) / ((1) + (Math.pow((10), ((Rb - Ra) / (400))))); const Eap = Ea * 100; document.querySelector('#result').textContent = Eap; })
<input id="input1"> <input id="input2"> <button id="button">update</button> <p>result: <span id="result"></span></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.