知识点:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script> window.onload = function() { //1.根据ID查询一个节点 //2.根据标签名查询一组节点 //3.根据NAME查询一组节点 var inputs = document.getElementsByName("sex"); console.log(inputs); //4.根据层次查询节点 //查询某节点的亲属(父亲、孩子、兄弟) //4.1查询节点的父亲 var gz = document.getElementById("gz"); var ul = gz.parentNode; console.log(ul); //4.2查询节点的孩子 //带空格 console.log(ul.childNodes); //不带空格 console.log(ul.getElementsByTagName("li")); //4.3查询节点的兄弟 //节点.parentNode.getElementsByTagName("")[i] var li = gz.parentNode.getElementsByTagName("li")[4]; console.log(li); } function f1() { //1.创建节点li var li = document.createElement("li"); li.innerHTML = "杭州"; //2.追加节点 var ul = document.getElementById("city"); ul.appendChild(li); } function f2() { //1.创建节点 var li = document.createElement("li"); li.innerHTML = "苏州"; //2.插入节点 var ul = document.getElementById("city"); var gz = document.getElementById("gz"); ul.insertBefore(li,gz); } function f3() { //获取要删除的节点的父亲 var ul = document.getElementById("city"); //获取要删除的节点 var gz = document.getElementById("gz"); //根据父亲删除孩子 ul.removeChild(gz); } </script> </head> <body> <p> <input type="radio" name="sex"/>男 <input type="radio" name="sex"/>女 </p> <p> <input type="button" value="追加" onclick="f1();"/> <input type="button" value="插入" onclick="f2();"/> <input type="button" value="删除" onclick="f3();"/> </p> <ul id="city"> <li>北京</li> <li>上海</li> <li id="gz">广州</li> <li>深圳</li> <li>天津</li> </ul> </body> </html>
下拉框选择案例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script> var cities; window.onload = function() { //模拟加载所有的城市 cities = [ ["石家庄","保定","廊坊"], ["济南","青岛","威海"], ["南京","苏州","无锡"] ]; } function chg() { console.log(1); //获取选择的省份(序号) var s1 = document.getElementById("province"); var index = s1.value; //获取该省份对应的城市 var pcities = cities[index]; //删除旧的城市 var s2 = document.getElementById("city"); //var options = // s2.getElementsByTagName("option"); //for(var i=options.length-1;i>=1;i--) { // s2.removeChild(options[i]); //} s2.innerHTML = "<option>请选择</option>"; //追加新的城市 if(pcities) { for(var i=0;i<pcities.length;i++) { var option = document.createElement("option"); console.log(pcities[i]); option.innerHTML = pcities[i]; s2.appendChild(option); } } } </script> </head> <body> 省: <select onchange="chg();" id="province"> <option value="-1">请选择</option> <option value="0">河北省</option> <option value="1">山东省</option> <option value="2">江苏省</option> </select> 市: <select id="city"> <option>请选择</option> </select> </body> </html>
Unit07: document 对象 、 自定义对象 、 事件
原文:http://www.cnblogs.com/tangshengwei/p/6395908.html