简体   繁体   English

将JavaScript打印到HTML文档

[英]Printing JavaScript to HTML doc

JavaScript homework assignment requests "display the results in the document window". JavaScript作业分配请求“在文档窗口中显示结果”。 I am assuming it means to print out the JS answers on an HTML doc and not a pop-up. 我假设这意味着在HTML文档而不是弹出窗口上打印出JS答案。

I can get this code to work in the console, but have absolutely no idea how to get it to print on an HTML doc. 我可以让此代码在控制台中工作,但绝对不知道如何将其打印在HTML文档上。 From what I've read, using document.write is bad form and "return" doesn't seem to work. 根据我的阅读,使用document.write是错误的形式,“返回”似乎不起作用。 Any suggestions? 有什么建议么?

for (var i = 1; i <= 10; i++) {
  var mm = (i * 25.4);
  console.log (i + " inches = " + Math.round(100 * mm) / 100 + " millimeters"); 
}

Also, is there a way for all the numbers to print out the 10ths place integer? 另外,有没有一种方法可以将所有数字打印出第十位的整数? Notice in the results below, at "5 inches," it only prints the whole number, I'd like it to print 127.0 to keep the numbers consistent. 请注意,在下面的结果中,“ 5英寸”仅打印整数,我希望打印127.0以保持数字一致。

3 inches = 76.2 millimeters
4 inches = 101.6 millimeters
5 inches = 127 millimeters

Thanks in advance. 提前致谢。

If you don't want to use document.write you can create a HTML element and then add a value to it with Javascript. 如果您不想使用document.write ,则可以创建一个HTML元素,然后使用Javascript向其中添加一个值。 Also you can use toFixed to format the number. 您也可以使用toFixed格式化数字。 For example: 例如:

HTML 的HTML

<div id="hello"></div>

Javascript Java脚本

document.getElementById("hello").innerHTML = "";
for (var i = 1; i <= 10; i++) {
    var mm = (i * 25.4);
    document.getElementById("hello").innerHTML += i + " inches = " + (Math.round(100 * mm) / 100).toFixed(1) + " millimeters <br />";
}

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

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