DOM and form stripping operation

First, the concept
1, the DOM
the DOM: the Document Object Model Document Object Model
for dynamic interactivity of the page, bom operation is not enough, need to operate html is the core. How htm, is the DOM. Simply put, dom provides dynamic control program html interface. DOM Document Object Model depicts a hierarchical tree of nodes, run developers to add, remove, and modify certain part of the page. dom in the core of the javascript.
Each loaded in the browser's HTML document will become the Document object. Document object so that we can access all the elements in an HTML page from the script. Document objects are part of the Window object, and can be accessed by window.document property.
2, the node
when loading HTML pages, Web browser generates a tree structure that represents the internal structure of the page. Such DOM tree understood as nodes, nodes form a tree. For the elements in the page may be parsed into the following types of nodes:

节点类型       HTML内容                   例如
文档节点      文档本身                       整个文档document
元素节点       所有的HTML元素         a、div、p
属性节点       HTML元素内的属性     id、href、name、class
文本节点       元素内的文本               hello
注释节点       HTML中的注释           <!--   -->
16398174-d20af1d8528e8072.png
clipboard1.png

Second, the operating element node
when the HTML document is parsed into a DOM tree after every node inside can be seen as a one object, we become DOM objects, for these objects, we can make all kinds the operation, to find a certain class or a node objects, you can create some kind of node objects, you can add a node object in a certain position, or even delete nodes can be dynamically objects, these operations can make our page look dynamic effect , use late binding events, we can make our pages to perform specific transformations in particular at the time, specific events.

  1. Gets node
    performing add, delete, change operation, you need to specify a location, or find a target, then we can provide a method of the Document object, find, locate an object (that is, we say node ).
    Note: The operator must wait dom node initialized to perform. Handled in two ways:
    (1) the script calls the label can be moved to the end of html;
    (2) using the onload event to handle JS, wait for html loaded before loading the onload event in the JS.
方法                                        描述 
getElementById()                   根据 id 获取 dom 对象,如果 id 重复,那么以第一个为准 
getElementsByTagName()     根据标签名获取 dom 对象数组 
getElementsByClassName() 根据样式名获取 dom 对象数组 
getElementsByName()           根据 name属性值获取 dom 对象数组,常用于多选获取值 
  1. Creating nodes and insert nodes
    * Create node
方法                       描述 
createElement()    创建一个新的节点,需要传入节点的标签名称,返回创建的元素对象 
createTextNode()   创建一个文本节点,可以传入文本内容 innerHTML 
                               也能达到创建节点的效果,直接添加到指定位置了 
    *  插入节点 
方法                         描述 
write()                      将任意的字符串插入到文档中 
appendChild()         向元素中添加新的子节点,作为最后一个子节点 
insertBefore()          向指定的已有的节点之前插入新的节点 
                                    newItem:要插入的节点 
                                    exsitingItem:参考节点    需要参考父节点 
  /**
         * 替换元素
         */
        function replaceNode() {
            // oldNode.parentNode.replaceChild(newNode,oldNode) 
            // 首先通过旧节点定位到父节点,然后用新的节点替换旧节点
            var cxy = document.getElementById("test");
            // 创建新节点
            var span = document.createElement("span");
            span.innerHTML = "攻城狮";
            cxy.parentNode.replaceChild(span,cxy);
        }
        
        /**
         * cloneNode()      复制节点
                var 复制好的节点 = 被复制的节点.cloneNode([true/false]);
                true:深度克隆,可以克隆结构和内容
                false(默认值):只克隆结构
         */
        function cloneValue() {
            // 得到被克隆的对象
            var cloneValue = document.getElementById("music");
            var newValue = cloneValue.cloneNode(false); // 浅度克隆,只克隆结构
            console.log(newValue);
            var deepValue = cloneValue.cloneNode(true); // 克隆结构及内容
            console.log(deepValue);
            
            // 将克隆好的结果追加到div中
            document.getElementById("mydiv").appendChild(deepValue);
        }
         
  1. Indirect find nodes
方法|属性        描述 
childNodes ()   返回元素的一个子节点的数组 
firstChild()    返回元素的第一个子节点 
lastChild()     返回元素的最后一个子节点 
nextSibling     返回元素的下一个兄弟节点 
parentNode      返回元素的父节点 
previousSibling 返回元素的上一个兄弟节点 

// 得到div对象
var div1 = document.getElementById("div1");
// childNodes ()        返回元素的一个子节点的数组
console.log(div1.childNodes);
// firstChild()         返回元素的第一个子节点
console.log(div1.firstChild);
// lastChild()      返回元素的最后一个子节点
console.log(div1.lastChild);
// parentNode           返回元素的父节点
console.log(div1.parentNode);
// nextSibling      返回元素的下一个兄弟节点
console.log(div1.nextElementSibling); // 下一个元素节点(元素)
console.log(div1.nextSibling); // 下一个节点(包含文本节点)
//  previousSibling     返回元素的上一个兄弟节点
console.log(div1.previousElementSibling); // 上一个元素节点(元素)
console.log(div1.previousSibling); // 上一个节点(包含文本节点)
  1. Replacement Node
方法|属性 描述 
replaceChild(newNode,oldNode) 用新的节点替换旧的节点 
    oldNode.parentNode.replaceChild(newNode,oldNode) 
    首先通过旧节点定位到父节点,然后用新的节点替换旧节点
  1. Cloning node
方法|属性 描述 
cloneNode() 复制节点  
var 复制好的节点 = 被复制的节点.cloneNode([true/false]); 
    true:深度克隆,可以克隆结构和内容 
    false(默认值):只克隆结构 
  1. Delete nodes
    method | property description
    removeChild () to remove the child from the element node
    Third, the form action
    before one kind of form we are back to the page data transmission very common way during data transmission (request is made), we should now page to verify the legitimacy of a series of data, save unnecessary data transmission errors, and improve the user experience.
    1, to obtain Form
document.表单名称 
document.getElementById(表单 id);
document.forms[表单名称]
document.forms[索引]; //从 0 开始 
<body>  
    <form id='myform' name="myform" action="" method="post">
    </form> 
    <form id='myform2' name="myform2" action="" method="post">
    </form> 
</body> 
<script>  
    //四种方式  var form =document.getElementById("myform");  
    form =document.myform;  
    form =document.forms["myform"];  
    form =document.forms[0];  
    console.log(form); 
</script> 

2, to obtain elements
* Get the input element

1)、通过 id 获取:document.getElementById(元素 id); 
2)、通过 form.名称形式获取: myform.元素名称;    name 属性值 
3)、通过 name 获取 :document.getElementsByName(元素名称)[索引] //从 0 开始 
4)、通过 tagName 数组 :document.getElementsByTagName('input')[索引] //从 0 开始 
 
<body>  
    <form id='myform' name="myform" action="" method="get">     
    姓名:<input type="text" id="uname" name="uname" value="zs"/>
    <br />   
    密码:<input type="password" id="upwd" name="upwd" value="123456" />
    <br />   <input type="hidden" id="uno" name="uno" value="隐藏域" />   
    个人说明:<textarea name="intro"></textarea>   
    <button type="button" onclick="getTxt();" >
    获取元素内容</button>  
    </form> 
</body> 
<script>  
    function getTxt(){   
        var uno =document.getElementById("uno");   
        var uname =myform.uname;   
        console.log(uname+"--------");   
        var upwd =document.getElementsByTagName('input')[1] ;   
        var intro =document.getElementsByName("intro")[0];       
        alert(uno.value+"-->"+uname.value +"-->"+upwd.value+"->"+intro.value);  
      } 
 </script> 
    *  获取 单选按钮 
前提:将一组单选按钮设置相同的 name 属性值 
(1)获取单选按钮组:   document.getElementsByName("name 属性值");  
(2)遍历每个单选按钮,并查看单选按钮元素的 checked 属性   若
    属性值为 true 表示被选中,否则未被选中  
选中状态设定:  checked=’checked’  或  checked=’true’  或  checked  
未选中状态设定:   没有 checked 属性   或  checked=’false’  
<form action="" name="myform">  
    <input type="text" name="inputName" value="aaa" /> 
     <input type="radio" name="rad" value="1" /> 1  
     <input type="radio" name="rad" value="2"  /> 2 
 </form>    
<script type="text/javascript"> 
  var radios = document.getElementsByName('rad')  
  //radios[0].checked = 'checked'  
  for(var i=0; i<radios.length; i++){  
      console.log(radios[i].checked + '---' + radios[i].value) 
   } 
</script> 
    *  获取 多选按钮 
操作方式与单选同理,不同之处在于可以多选 
var ufav=document.getElementsByName("ufav"); var favstr="";     
for (i=0;i<ufav.length;i++){        
     if(ufav[i].checked){             
     favstr+=ufav[i].value+",";      
     }    
} 
favstr =favstr.substr(0,favstr.length-1); 
    *  获取下拉选项 
(1)获取 select 对象: var ufrom = document.getElementById("ufrom"); 
(2)获取选中项的索引: var idx=ufrom.selectedIndex ; 
(3)获取选中项 options 的 value 属性值: 
var val = ufrom.options[idx].value; 
注意:当通过 options 获取选中项的 value 属性值时,  
若没有 value 属性,则取 option 标签的内容  
若存在 value 属性,则取 value 属性的值 
(4)获取选中项 options 的 text: 
var txt = ufrom.options[idx].text; 
选中状态设定:selected='selected'、selected=true、selected 
未选中状态设定:不设 selected 属性   
<body>
        来自:
            <select id="ufrom" name="ufrom" >
                <option value="-1" >请选择</option>
                <option selected="selected">北京</option>
                <option value="1" >上海</option>
            </select><br />
    </body>
 <script type="text/javascript">
        // (1)获取 select 对象
        var sel = document.getElementById("ufrom");
        
        // (2)获取选中项的索引
        var selectIndex = sel.selectedIndex;
        console.log("当前选中项的索引:" + selectIndex);
        
        // (3)获取选中项 options 的 value 属性值
        var value1 = sel.value;
        var value2 = sel.options[selectIndex].value;
        console.log("当前选中项的值:" + value1 + "," + value2);
        
        // (4)获取选中项 options 的 text
        var text1 = sel.options[selectIndex].innerHTML;
        var text2 = sel.options[selectIndex].text;
        console.log("当前选中项的文本:" + text1 + "," + text2);
        
    </script> 

3, the form is submitted

注:提交表单时,表单元素必须设置name属性值
提交类型:
    get请求
        参数会直接跟在地址栏后面显示,请求参数的长度有限,相对post而言不安全,
            不会自动刷新缓存;每次访问时优先获取缓存中的数据,所以请求速度快。
    post请求 (需要服务器的支持)
        参数不会跟在地址栏后面显示,请求参数长度不限(其实是有长度限制,
            与服务器相关),相对而言安全,会自动刷新缓存;请求速度相对而言慢。
通常做查询操作,使用GET请求;增删改使用POST请求。
提交表单
    (1)使用普通 button 按钮+onclick 事件+事件中编写代码:
    获取表单.submit();
    (2)使用 submit 按钮 + onclick="return 函数()" +函数编写代码: 
    最后必须返回:return true|false;
    (3)使用 submit 按钮/图片提交按钮 + 表单 onsubmit="return 函数();" +函数编写代码: 
    最后必须返回:return true|false;
<form action="01-获取表单.html" method="get">
            姓名:<input type="text" name="uname" />
            <input type="submit" value="提交" onclick="return checkForm1()"/>
        </form>
        
        <form action="01-获取表单.html" method="get" onsubmit="return checkForm2()">
            姓名:<input type="text" name="uname" />
            <input type="submit" value="提交" />
        </form>
        
        <form action="01-获取表单.html" method="get" >
            姓名:<input type="text" name="uname1" />
            <input type="button" value="提交" onclick="checkForm3()" />
            <span id="msg" style="font-size: 12px;color: red;"></span>
</form>

<script type="text/javascript">
        /*提交方式一:submit按钮 + onclick事件*/
        // 给submit按钮绑定点击事件,调用时需要使用"return 函数名()",定义的函数中需要return true或false;
        //如果return true,则提交表单;return false不提交;若直接return也会提交表单
        function checkForm1() {
            //return true; // 提交表单
            return false; // 不提交表单
            //return; // 无效,不会阻止表单提交
        }
        
        
        /*提交方式二:submit按钮 + onsubmit事件*/
        // 给表单对象绑定onsubmit事件,调用时需要使用"return 函数名()",定义的函数中需要return true或false;
        //如果return true,则提交表单;return false不提交;若直接return也会提交表单
        function checkForm2() {
            return true; // 提交表单
            //return false; // 不提交表单
            //return; // 无效,不会阻止表单提交
        }
        
        /*提交方式三:button按钮+点击事件*/
        // 给button按钮绑定点击事件,调用时需要使用"函数名()",如果满足要求则手动提交表单,否则return
        function checkForm3() {
            var uname = document.getElementsByName("uname1")[0].value;
            if ( uname == null || uname.trim() == "") {
                console.log("用户名不能为空!");
                document.getElementById("msg").innerHTML = "用户名不能为空!";
                return;
            }
            
            // 手动提交表单
            document.forms[2].submit();
        }
        
        
    </script>

Reproduced in: https: //www.jianshu.com/p/eae50f3a5a74

Guess you like

Origin blog.csdn.net/weixin_33984032/article/details/91192454