10.4删除特定节点

来源:互联网 发布:干性皮肤洗面奶知乎 编辑:程序博客网 时间:2024/04/29 22:25

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
 var newBuild
 function execution(){
  document.forms[0].onsubmit = nodeChanger;
  newBuild = document.getElementById("newBuild");                     
 };
 function addElement(){
  var textareaValue = document.getElementById("textarea").value; //获取textarea的值
  var newText = document.createTextNode(textareaValue); //新建文本节点值为textarea的值
  var para = document.createElement("p"); //新建p元素节点
  para.appendChild(newText); //新建文本节点的值插入到新建的p元素里面
  newBuild.appendChild(para); //新建的p元素插入到id为newBuild的div里面
 };
 function deleteElement(){
  var listOption = document.getElementById("listOption").selectedIndex; //获取select下拉列表索引
  var allp = document.getElementsByTagName("p"); //获取p元素
  var replanting = allp.item(listOption); //设置p元素为select下拉列表索引 将p元素和下拉列表索引对应
  newBuild.removeChild(replanting); //从id为newBuild的div内删除p元素为select下拉列表索引的元素
 };
 function nodeChanger(){
  var actionType = -1; //初始化actionType为-1
  var newPara = newBuild.getElementsByTagName("p").length; alert("a");//从id为newBuild的div对象中获取所有p元素节点的长度
  var myInput = document.forms[0].radioAction; // 获取所有的单选按钮
 
  for(var i=0;i<myInput.length;i++){  //循环遍历素有单选按钮
   if(myInput[i].checked){ //如果按钮选中  
     actionType = i; //设置acitionType值为i
   }                 //由于i是数组myInput的索引 所用用switch来判断i的值 如果为0就是获取到了第一个input元素                         
  };                                                              //如果为1就是获取到了第二个input元素
  switch(actionType){ //循环遍历所有单选按钮
   case 0:            //如果actionType值为0 也就是选中
    addElement();   //执行addElement函数 这个函数的作用是把textarea的值插入到新建的p元素内再把p元素插入到id为newBuild的div内
 break;
   case 1:          //如果actionType值为1 也就是选中 
    if(newPara > 0){ //如果id为newBuild的div内的p元素的长度大于0 也就是有至少一个p元素
  deleteElement(); //执行deleteElement函数 这个函数的作用是设置p元素为select下拉列表索引 并且从id为newBuild的div内删除为下拉列表索引的p元素
  break;          
 }                 
   default:          
    alert("No valid action was chosen");  
  };
 
  document.getElementById("listOption").options.length = 0; //初始化下拉列表长度为0
  for(var i = 0; i<newBuild.getElementsByTagName("p").length; i++){ //遍历id为newBuild的div内部的p元素
    document.getElementById("listOption").options[i] = new Option(i+1)  //下拉列表的选项为新建的选项的索引加1;
  }
  return false;
 };    
 window.onload = execution;             
</script>
</head>

<body>
<form action="#">
 <textarea id="textarea" rows="5" cols="25"></textarea>
 <input type="radio" name="radioAction" />添加
 <input type="radio" name="radioAction" />删除
 序列号:<select id="listOption"></select>
 <input type="submit" value="Submit"/>
</form>
<div id="newBuild"></div>
</body>
</html>

 

0 0
原创粉丝点击