Javascript是目前最流行的服务器脚本语言,使用Javascript可以为网页添加丰富的逻辑和更加复杂动态效果。
代码整理自w3school:http://www.w3school.com.cn
效果图:
示例代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>Javascript 简介</title>
<head type="text/css">
<style>
body {background-color:#e0e0e0}
p.nowrap {display:inline;padding-left:10px}
</style>
</head>
<body>
<h3>(一)写入 HTML 输出</h3>
<script>
document.write("<h2>This is a h2-line.</h2>");
document.write("<p>This is a paragraph.</p>");
</script>
<h3>(二)事件响应</h3>
<p>JavaScript 能够对事件作出反应。比如对按钮的点击:</p>
<button type="button" οnclick="alert('Welcome!')">点击这里</button>
<h3>(三)改变 HTML 内容</h3>
<p id="test_content">这是一行作为示例的文字</p>
<script>
function changeHtmlContent(){
x = document.getElementById("test_content");
x.innerHTML = "Hello Javascript!";
}
</script>
<button type="button" οnclick="changeHtmlContent()">点击按钮,改变网页内容</button>
<h3>(四)改变 HTML 组件的属性</h3>
<p>点击灯泡,控制开关状态:</p>
<img id="light" src="images/eg_bulboff.gif" width="80px" height="120px" οnclick="changeImage()">
<script>
function changeImage(){
element = document.getElementById("light");
if (element.src.match("bulbon")){
element.src="images/eg_bulboff.gif";
}else{
element.src="images/eg_bulbon.gif"
}
}
</script>
<p id="text_to_changeColor">点击按钮,改变文字颜色<p>
<button type="button" οnclick="changeColor()">改变颜色</button>
<script>
function changeColor(){
element = document.getElementById("text_to_changeColor");
element.style.color="#FF0000"
}
</script>
<h3>(五)验证输入</h3>
<input id="numberText" type="text"/>
<input type="submit" value="确认" οnclick="testInput()"/><p class="nowrap" id="isOK"></p>
<script>
function testInput(){
var x = document.getElementById("numberText").value;
if (x==""){
alert("请输入内容")
}else if(isNaN(x)){
alert("不是数字类型!")
}else{
document.getElementById("isOK").innerHTML="输入正确";
}
}
</script>
</body>
</html>