首页 > 解决方案 > 如何在 HTML 中打印 JavaScript 函数的返回值?

问题描述

我正在创建一个代码,用户可以在其中计算矩形的面积。在提示时输入高度和宽度后,站点应在表格中打印高度、宽度和面积值。高度和宽度代码可以正常工作和打印,但该区域不会打印。我哪里错了?

这是单独的 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">&nbsp;<script>document.write(height);</script></td></tr>
<tr><td  class="makert">Width:</td>
<td class="makectr">&nbsp;<script>document.write(width);</script></td></tr>
<tr><td  class="makert">Area:</td>
<td class="makectr">&nbsp;<script>document.write(area);</script></td></tr>
</table>

标签: javascripthtml

解决方案


你应该使用你的功能:

<script>document.write(calcArea(height,  width));</script>

声明函数的目的是为了以后使用它。


推荐阅读