简体   繁体   English

如何打印出变量?

[英]how to Print out variable?

I'm really new to JS.我真的是 JS 的新手。 I am working on the if else statement and returning the total using the button.我正在处理 if else 语句并使用按钮返回总数。 I also want to return some other input from HTML file also using the same button or on the same function as my calculate function. How do I return the total amount, name(input), number(input), from html to that one button as well?我还想从 HTML 文件返回一些其他输入,也使用与我计算 function 相同的按钮或相同的 function。如何将总额、名称(输入)、数字(输入)从 html 返回到那个按钮还有吗?

If you don't get my question please run the code and see that it is not printing out the other input value.如果您不明白我的问题,请运行代码并查看它是否没有打印出其他输入值。 Thank you for helping me out.谢谢你帮我。

 function calculate() { var total var kwh = parseFloat(document.getElementById("kw").value); if (kwh <= 50) { total = (kwh * 500); } else if (kwh <= 100) { total = kwh * 1000; } else { total = kwh * 2120; } document.getElementById("total").innerHTML = total; }
 <body> <div> <label>ឈ្មោះអតិថិជន:</label> <input id="name" type="text" placeholder="ឈ្មោះអតិថិជន"> </div> <div> <label>ឈ្មោះអតិថិជន:</label> <input type="number" placeholder="លេខអតិថិជន"> </div> <div> <label>ឈ្មោះអតិថិជន:</label> <input type="number" placeholder="kwh" id="kw"> </div> <button type="button" onclick="calculate()">គណនា</button> <p>Result: <span id="total"></span></p> <p>Name: <span id="name"></span></p> <.-- <script src="script2.js"></script> --> </body>

You are very close just need a few tweaks.您非常接近,只需要进行一些调整。

You shouldn't repeat ids, so in that case, to make it easier to understand, we can rename the input with id name to name_input , so you can retrieve its value as你不应该重复 ids,所以在这种情况下,为了更容易理解,我们可以将带有 id name的输入重命名为name_input ,这样你就可以检索它的值作为

document.getElementById('name_input').value

You can add that to your function and assign it to the innerHTML of name inside the function calculate() and so on with as many actions as you want您可以将其添加到您的 function 并将其分配给 function calculate()name的 innerHTML,依此类推,并执行任意数量的操作

Working snippet:工作片段:

 function calculate() { var total var kwh = parseFloat(document.getElementById("kw").value); if (kwh <= 50) { total = (kwh * 500); } else if (kwh <= 100) { total = kwh * 1000; } else { total = kwh * 2120; } document.getElementById("total").innerHTML = total; document.getElementById("name").innerHTML = document.getElementById("name_input").value; }
 <body> <div> <label>ឈ្មោះអតិថិជន:</label> <input id="name_input" type="text" placeholder="ឈ្មោះអតិថិជន"> </div> <div> <label>ឈ្មោះអតិថិជន:</label> <input type="number" placeholder="លេខអតិថិជន"> </div> <div> <label>ឈ្មោះអតិថិជន:</label> <input type="number" placeholder="kwh" id="kw"> </div> <button type="button" onclick="calculate()">គណនា</button> <p>Result: <span id="total"></span></p> <p>Name: <span id="name"></span></p> <.-- <script src="script2.js"></script> --> </body>

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

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