一、HTML DOM 元素(节点)
1、创建新的 HTML 元素
如需向 HTML DOM 添加新元素,您必须首先创建该元素(元素节点),然后向一个已存在的元素追加该元素。
<div id="div1">
<p id="p1">1</p>
<p id="p2">2</p>
</div>
<script type="text/javascript">
var para =document.createElement("p");
var node =document.createTextNode("这是一个新段落。");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChlid(para);
</script>
2、删除已有的 HTML 元素
<div id="div1">
<p id="p1">1</p>
<p id="p2">2</p>
</div>
<script type="text/javascript">
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
二、JavaScript 对象
1、访问对象的属性
objectName.propertyName
2、访问对象的方法
objectName.methodName()
3、使用对象构造器
<div id="div1">
<p id="p1">1</p>
<p id="p2">2</p>
</div>
<script type="text/javascript">
var person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
document.write(person.firstname+" is "+person.age+" years old.");
</script>
4、把属性添加到 JavaScript 对象
person.firstname="John";
person.lastname="Doe";
person.age=30;
person.eyecolor="blue";
x=person.firstname;
5、把方法添加到 JavaScript 对象
<script>
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
function changeName(name){
this.lastname=name;
}
}
myMother=new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.write(myMother.lastname);
</script>
6、JavaScript for...in 循环
语法
for (variable in object)
{
执行的代码……
}
for...in 循环中的代码块将针对每个属性执行一次。
<button onclick="myFunction()">点击</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction(){
var x;
var txt="";
var person={fname:"Bill",lname:"Gates",age:56};
for (x in person){
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script>
三、JavaScript Number 对象
1、
<button onclick="myFunction()">点击</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction(){
var x=2+3;
document.getElementById("demo").innerHTML=x;
}
</script>
2、
<script type="text/javascript">
var myNumber=128;
document.write(myNumber);
document.write(myNumber.toString(16));
document.write(myNumber.toString(8));
document.write(myNumber.toString(2));
</script>
3、
<script type="text/javascript">
var carname1="a";
var carname2="b";
var answer1="c";
var answer2="d";
var answer3="e";
document.write(carname1+"<br>")
document.write(carname2+"<br>")
document.write(answer1+"<br>")
document.write(answer2+"<br>")
document.write(answer3+"<br>")
</script>
网友评论