改變內(nèi)容(點擊事件)
document.getElementByID(“some id”):
這個方法是 HTML DOM 中定義的,用于改變HTML中的內(nèi)容。
演示
代碼如下:
<html>
<body>
<h1>我的第一段 JavaScript</h1>
<p id="demo">
JavaScript 能改變 HTML 元素的內(nèi)容搭幻。
</p>
<script>
function myFunction()
{
x=document.getElementById("demo"); // 找到元素
x.innerHTML="Hello JavaScript!"; // 在id 是demo的標(biāo)記那里顯示"Hello JavaScript!";
}
</script>
<button type="button" onclick="myFunction()">點擊這里</button>
</body>
</html>
Javascript 數(shù)組
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var arr = [1,2,3,4,5];//整數(shù)數(shù)組
//alert(arr);
//alert(arr[4]);
var arr2 = ["html","js","sql","java","test"];//字符串?dāng)?shù)組
alert(arr2);
alert(length);
</script>
</head>
<body>
</body>
</html>
作業(yè)練習(xí)
增加段落(子節(jié)點):createElement
刪除段落(子節(jié)點):childNodes
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var i = 0;//統(tǒng)計添加按鈕的點擊次數(shù)
function myfunction(){
i++;//i+1
var parent = document.getElementById("div1");//找到id等于div1的盒子
var child = document.createElement("p");//創(chuàng)建一個段落元素
var n = i+1;
child.innerText="這是第"+n+"個段落";//+n+ “+”起到拼接內(nèi)容作用
parent.appendChild(child);
}
function remove(){
var parent = document.getElementById("div1");//找到div節(jié)點
var childs = parent.childNodes;//得到該節(jié)點里面的所有子節(jié)點
var count = childs.length;//獲取該數(shù)組里面的元素個數(shù)
var lastnode=childs[count-1];//得到最后一個子節(jié)點(段落)
parent.removeChild(lastnode);
}
</script>
</head>
<body>
<div id="div1">
<p id="p001">我的第一段javascript</p>
</div>
<button type="button" onclick="myfunction()">創(chuàng)建一個新段落</button>
<button type="button" onclick="remove()">刪除一個段落</button>
</body>
</html>
效果如圖: