首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在HTML中打印JavaScript函数的返回值?

问如何在HTML中打印JavaScript函数的返回值?
EN

Stack Overflow用户
提问于 2019-01-30 04:31:30
回答 4查看 3.9K关注 0票数 1

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

下面是单独的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代码。

代码语言:javascript
复制
<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>
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-01-30 04:34:45

你应该使用你的函数:

代码语言:javascript
复制
<script>document.write(calcArea(height,  width));</script>

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

票数 5
EN

Stack Overflow用户

发布于 2019-01-30 04:33:14

这是因为area是calcArea方法的局部变量,而document对象无权访问它。

代码语言:javascript
复制
var area = 0;
var height = prompt("Please enter the height");
var width = prompt("Please enter the width");

尝试下面的代码,因为上面的方法并不是一种实用的编码方式:

代码语言:javascript
复制
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;
})();
代码语言:javascript
复制
<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>

​

票数 3
EN

Stack Overflow用户

发布于 2019-01-30 04:33:24

area变量是在函数内部声明的,因此它不存在于函数作用域之外。

试试这样的东西

代码语言:javascript
复制
var area = "...";

function calcArea(height,  width) {
  area = height * width;
  return area;
} 

而且你的函数从来不会被调用,所以面积实际上也不会被赋值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54429137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档