1.使用window.alert()弹出警告框
源代码:
<html>
<body>
<h1>这是我的世界,欢迎大家前来!</h1>
<script>window.alert("哈哈,我来了!")</script>
</body>
</html>
运行结果:
2.使用document.write()方法将内容写到HTML页面中
源代码:
<html>
<body>
<h1>这是我的世界,欢迎大家前来!</h1>
<script>document.write("哈哈,我来了!")</script>
</body>
</html>
运行结果:
注意:
如果在文档已完成加载后执行document.write()方法,整个html页面将被覆盖
源代码:
<html>
<body>
<h1>文档加载完毕,点击确定按钮,执行test方法中的内容</h1>
<input type="button" onclick="test()" value="确定">
<script>
function test(){
document.write("<h3>注意,注意,注意,覆盖了整个HTML页面!<h3>");
}
</script>
</body>
</html>
运行结果:
点击确定:
3.使用innerHTML写入到html元素(标签)中
在js中,如果想要获取到某个HTML元素,可以使用document.getElementById(id)
id:元素中id属性值(id属性值一般是唯一的,避免重复)
通过innerHTML可以获取、插入元素的内容:
(1) 获取元素的内容
源代码
<html>
<body>
<h1 id="title">这是一个标题</h1>
<input type="button" onclick="test()" value="确定">
<script>
function test(){
content=document.getElementById("title").innerHTML;
alert(content);
}
</script>
</body>
</html>
运行结果:
点击确定:
(2) 插入内容
源代码:
<html>
<body>
<h1 id="title">这是一个标题</h1>
<input type="button" onclick="test()" value="确定">
<script>
function test(){
document.getElementById("title").innerHTML="hello world";
}
</script>
</body>
</html>
运行结果:
点击确定:
4.使用console.log()写入到浏览器的控制台
源代码:
<html>
<body>
<h1>在浏览器中按F12启用调试模式,点击console菜单</h1>
<script>
console.log("hello world");
</script>
</body>
</html>
运行结果: