[英]How can I make the Javascript console NOT print the return value of a function
[英]How can I print the return value of a JavaScript function in HTML?
我正在创建一个代码,用户可以在其中计算矩形的面积。 在提示时输入高度和宽度后,站点应在表格中打印高度,宽度和面积值。 高度和宽度代码可以正常工作并打印,但是不会打印该区域。 我要去哪里错了?
这是单独的JavaScript代码。
var height = prompt("Please enter the height");
var width = prompt("Please enter the width");
function calcArea(height, width) {
var area = height * width;
return area;
}
这是在其中编码JavaScript输出的HTML代码。
<table>
<caption>Calculate the Area of a Rectangle</caption>
<tr><td class="makert">Height:</td>
<td class="makectr"> <script>document.write(height);</script></td></tr>
<tr><td class="makert">Width:</td>
<td class="makectr"> <script>document.write(width);</script></td></tr>
<tr><td class="makert">Area:</td>
<td class="makectr"> <script>document.write(area);</script></td></tr>
</table>
您应该使用函数:
<script>document.write(calcArea(height, width));</script>
声明一个函数的重点是稍后使用它。
这是因为area是calcArea
方法的局部变量, document
对象无权访问它。
var area = 0;
var height = prompt("Please enter the height");
var width = prompt("Please enter the width");
请改用此代码,因为上述方法不是实际的编码方法:
var height = prompt("Enter Height: "); var width = prompt("Enter Width: "); (function calcArea() { var area = +height * +width; document.getElementsByClassName('makectr')[0].innerHTML = height; document.getElementsByClassName('makert')[1].innerHTML = width; document.getElementsByClassName('makectr')[2].innerHTML = area; })();
<table> <caption>Calculate the Area of a Rectangle</caption> <tr> <td class="makert">Height: </td> <td class="makectr"></td> </tr> <tr> <td class="makert">Width: </td> <td class="makectr"></td> </tr> <tr> <td class="makert">Area: </td> <td class="makectr"></td> </tr> </table>
area
变量是在函数内部声明的,因此它不在函数范围之外。
试试这个
var area = "...";
function calcArea(height, width) {
area = height * width;
return area;
}
您的函数也永远不会被调用,因此area实际上不会被赋值。
您可以使用以下代码来计算值并分离JS和HTML
var q= s=>document.querySelector(s); function calcArea(height, width) { var area = height * width; q('.heigh').innerHTML=height; q('.width').innerHTML=width; q('.area').innerHTML=area; return area; } function btnClick() { var height = prompt("Please enter the height"); var width = prompt("Please enter the width"); calcArea(height, width); q('table').style.display='block' }
<table style="display:none"> <caption>Calculate the Area of a Rectangle</caption> <tr><td class="makert">Height: </td><td class="heigh makectr"></td></tr> <tr><td class="makert">Width: </td><td class="width makectr"></td></tr> <tr><td class="makert">Area: </td><td class="area makectr"></td></tr> </table> <button onclick="btnClick()">Calc area</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.