JavaScript学习之JS简介

2025-11-04 18:56:02

1、JavaScript:写入 HTML 输出

<!DOCTYPE html>

<html>

<body>

JavaScript 能够直接写入 HTML 输出流中:

<script>

document.write("<h1>This is a heading</h1>");

document.write("This is a paragraph.");

</script>

您只能在 HTML 输出流中使用 <strong>document.write</strong>。

如果您在文档已加载后使用它(比如在函数中),会覆盖整个文档。

</body>

</html>

JavaScript学习之JS简介

2、JavaScript:对事件作出反应

<!DOCTYPE html>

<html>

<body>

<h1>我的第一段 JavaScript</h1>

JavaScript 能够对事件作出反应。比如对按钮的点击:

<button type="button" onclick="alert('Welcome!')">点击这里</button>

</body>

</html>

JavaScript学习之JS简介

JavaScript学习之JS简介

3、JavaScript:改变 HTML 内容

<!DOCTYPE html>

<html>

<body>

<h1>我的第一段 JavaScript</h1>

<p id="demo">

JavaScript 能改变 HTML 元素的内容。

<script>

function myFunction()

{

x=document.getElementById("demo");  // 找到元素

x.innerHTML="Hello JavaScript!";    // 改变内容

}

</script>

<button type="button" onclick="myFunction()">点击这里</button>

</body>

</html>

JavaScript学习之JS简介

JavaScript学习之JS简介

4、JavaScript:改变 HTML 图像

<!DOCTYPE html>

<html>

<body>

<script>

function changeImage()

{

element=document.getElementById('myimage')

if (element.src.match("bulbon"))

  {

  element.src="/i/eg_bulboff.gif";

  }

else

  {

  element.src="/i/eg_bulbon.gif";

  }

}

</script>

<img id="myimage" onclick="changeImage()" src="/i/eg_bulboff.gif">

点击灯泡来点亮或熄灭这盏灯

</body>

</html>

JavaScript学习之JS简介

JavaScript学习之JS简介

5、JavaScript:改变 HTML 样式

<!DOCTYPE html>

<html>

<body>

<h1>我的第一段 JavaScript</h1>

<p id="demo">

JavaScript 能改变 HTML 元素的样式。

<script>

function myFunction()

{

x=document.getElementById("demo") // 找到元素

x.style.color="#ff0000";          // 改变样式

}

</script>

<button type="button" onclick="myFunction()">点击这里</button>

</body>

</html>

JavaScript学习之JS简介

JavaScript学习之JS简介

6、JavaScript:验证输入

<!DOCTYPE html>

<html>

<body>

<h1>我的第一段 JavaScript</h1>

请输入数字。如果输入值不是数字,浏览器会弹出提示框。

<input id="demo" type="text">

<script>

function myFunction()

{

var x=document.getElementById("demo").value;

if(x==""||isNaN(x))

{

alert("Not Numeric");

}

}

</script>

<button type="button" onclick="myFunction()">点击这里</button>

</body>

</html>

JavaScript学习之JS简介

JavaScript学习之JS简介

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢