在 JavaScript 中,值可以通过多种方式显示在页面上供用户查看:使用 document.write() 输出内容;使用 console.log() 打印内容到控制台;使用 innerHTML 插入内容到指定 ID 的 HTML 元素中;使用 textContent 插入内容到指定 ID 的 HTML 元素中(不包含 HTML 标记);使用 createElement() 创建新的 HTML 元素,设置内容并添加到指定 ID 的 HTML 元素中。

在页面上显示 JS 中的值
在 JavaScript 中,可以将值显示在页面上,以供用户查看。有几种方法可以做到这一点:
1. 使用 document.write()
document.write("内容");这是在页面上输出内容最简单的方法。
2. 使用 console.log()
console.log("内容");这将把内容打印到浏览器的开发者工具的控制台中。
3. 使用 innerHTML
document.getElementById("元素ID").innerHTML = "内容";这将把内容插入到具有指定 ID 的 HTML 元素中。
康通B2C网站管理系统康通购物网KtShopV1.5(Struts2+Hibernate+Spring+MySQL)版采用当前最流行的技术平台。前台:1、会员功能:注册会员,修改会员资料;登录系统后可以选购商品,放入购物车(修改购物数量、删除购物车里的内容),继续购物,最后确认下订单,在线支付(支付宝/财付通/网银在线)所选商品所选商品所需支付的金额;2、新闻频道功能:最新新闻,新闻列表及页面显示
4. 使用 textContent
document.getElementById("元素ID").textContent = "内容";这将把内容插入到具有指定 ID 的 HTML 元素中,但不包括 HTML 标记。
5. 使用 createElement()
const element = document.createElement("元素类型");
element.textContent = "内容";
document.getElementById("父元素ID").appendChild(element);这将创建一个新的 HTML 元素,设置其内容,并将其添加到具有指定 ID 的 HTML 元素中。
示例:
const name = "John Doe"; // 使用 document.write() document.write(`${name}
`); // 使用 console.log() console.log(name); // 使用 innerHTML document.getElementById("greeting").innerHTML = `Hello, ${name}!`; // 使用 textContent document.getElementById("name").textContent = name; // 使用 createElement() const newElement = document.createElement("p"); newElement.textContent = `Welcome, ${name}!`; document.getElementById("container").appendChild(newElement);
这将产生以下输出:
- 页面顶部显示一个
元素,其中包含名称 "John Doe"。 - 在浏览器的开发者工具中,控制台打印了名称 "John Doe"。
- 页面上有一个
div元素,其中包含 "Hello, John Doe!"。 - 页面上有一个
p元素,其中包含 "Welcome, John Doe!"。









