JavaScript 基础

来源:互联网 发布:山东大学 李利平 知乎 编辑:程序博客网 时间:2024/06/02 02:57

JavaScript 简介

JavaScript 是脚本语言
JavaScript 是一种轻量级的编程语言。
JavaScript 是可插入 HTML 页面的编程代码。
JavaScript 插入 HTML 页面后,可由所有的现代浏览器执行。
JavaScript 很容易学习。

JavaScript:写入 HTML 输出

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

JavaScript:对事件作出反应

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

alert() 函数在 JavaScript 中并不常用,但它对于代码测试非常方便。

JavaScript:改变 HTML 内容

x=document.getElementById("demo")  //查找元素x.innerHTML="Hello JavaScript";    //改变内容

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"><p>点击灯泡来点亮或熄灭这盏灯</p></body></html>

JavaScript:改变 HTML 样式

x=document.getElementById("demo")  //找到元素x.style.color="#ff0000";           //改变样式

JavaScript:验证输入

<!DOCTYPE html><html><body><h1>我的第一段 JavaScript</h1><p>请输入数字。如果输入值不是数字,浏览器会弹出提示框。</p><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>
if isNaN(x) {alert("Not Numeric")};
原创粉丝点击