我正在创建一个代码,用户可以在其中计算矩形的面积。在提示时输入高度和宽度后,站点应在表格中打印高度、宽度和面积值。高度和宽度代码可以正常工作和打印,但无法打印该区域。我哪里错了?
下面是单独的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>发布于 2019-01-30 04:34:45
你应该使用你的函数:
<script>document.write(calcArea(height, width));</script>声明函数的目的是为了在以后使用它。
发布于 2019-01-30 04:33:14
这是因为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>
发布于 2019-01-30 04:33:24
area变量是在函数内部声明的,因此它不存在于函数作用域之外。
试试这样的东西
var area = "...";
function calcArea(height, width) {
area = height * width;
return area;
} 而且你的函数从来不会被调用,所以面积实际上也不会被赋值。
https://stackoverflow.com/questions/54429137
复制相似问题