当前位置:网站首页>JS中表单操作、addEventListener事件监听器

JS中表单操作、addEventListener事件监听器

2022-08-09 22:05:00 可可鸭~

一、知识点1:

༼ つ ◕_◕ ༽つaddEventListener事件监听器

从菜鸟教程
HTML DOM addEventListener() 方法

document.getElementById("myBtn").addEventListener("click", function(){
    
    document.getElementById("demo").innerHTML = "Hello World";
});

语法

//[]代表选传参数
element.addEventListener(event, function, [useCapture]) //useCapture 默认为false就是冒泡.true 事件捕获阶段

useCapture是可选参数,默认值为false,它代表:控制监听器是在捕获阶段执行还是在冒泡阶段执行,通常我们都没传递第三个参数(传 true 的情况太少了)。目前DOM 规范做了修订:addEventListener() 的第三个参数可以是个对象值了,也就是说第三个参数现在可以是两种类型的值了:

addEventListener(type, listener,[ useCapture ])
addEventListener(type, listener,[ options ])

第三参数为对象值的情况,目前规范中 options 对象可用的属性有三个:

document.addEventListener(type, fn, {
    
    capture: false,
    passive: false,
    once: false
})

参数值
event事件
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">

    <title>Event.type Example</title>

    <script>
        var currEvent = null;
        function getEvtType(evt) {
    
            console.log("//Start------------getEvtType(evt)------------ ");

            currEvent = evt.type;
            console.log(currEvent);

            //document.getElementById("Etype").firstChild.nodeValue = currEvent;
            document.getElementById("Etype").innerHTML = currEvent;

            console.log("//End--------------getEvtType(evt)------------ ");
        }

        //Keyboard events
        document.addEventListener("keypress", getEvtType, false); //[second]

        document.addEventListener("keydown", getEvtType, false); //first
        document.addEventListener("keyup", getEvtType, false); //third

        //Mouse events
        document.addEventListener("click", getEvtType, false); // third

        document.addEventListener("mousedown", getEvtType, false); //first
        document.addEventListener("mouseup", getEvtType, false); //second

    </script>
</head>

<body>

<p>Press any key or click the mouse to get the event type.</p>
<p>Event type: <span id="Etype" style="color:red">-</span></p>

</body>
</html>

冒泡阶段
由子元素向父元素执行

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <style>
      .capture_1 {
    
        width: 200px;
        height: 200px;
        background-color: pink;
      }
      .capture_2 {
    
        width: 150px;
        height: 150px;
        background-color: rgb(88, 174, 224);
      }
      .capture_3 {
    
        width: 100px;
        height: 100px;
        background-color: rgb(58, 216, 105);
      }
      .capture_4 {
    
        width: 50px;
        height: 50px;
        background-color: rgb(241, 38, 38);
      }
    </style>
        <div class="capture_1" id="capture_1">
            1
            <div class="capture_2" id="capture_2">
              2
              <div class="capture_3" id="capture_3">
                3
                <div class="capture_4" id="capture_4">4</div>
              </div>
            </div>
          </div>
    <script>
      var fang1 = document.getElementById("capture_1");
      var fang2 = document.getElementById("capture_2");
      var fang3 = document.getElementById("capture_3");
      var fang4 = document.getElementById("capture_4");
            
      fang1.addEventListener(
        "click",
        function (e) {
    
          console.log(1);
        },
        false
      );
      fang2.addEventListener(
        "click",
        function (e) {
    
          console.log(2);
        },
        false
      );
      fang3.addEventListener(
        "click",
        function (e) {
    
          console.log(3);
        },
        false
      );
      fang4.addEventListener(
        "click",
        function (e) {
    
          console.log(4);
        },
        false
      );
    </script>
  </body>
</html>

在这里插入图片描述

捕获阶段
由父元素向子元素执行
在这里插入图片描述

当既有冒泡也有捕获
先执行捕获,也就是从父元素到子元素,然后在执行冒泡也就是子元素到父元素

//当1,3为冒泡,2,4为捕获时
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <style>
      .capture_1 {
    
        width: 200px;
        height: 200px;
        background-color: pink;
      }
      .capture_2 {
    
        width: 150px;
        height: 150px;
        background-color: rgb(88, 174, 224);
      }
      .capture_3 {
    
        width: 100px;
        height: 100px;
        background-color: rgb(58, 216, 105);
      }
      .capture_4 {
    
        width: 50px;
        height: 50px;
        background-color: rgb(241, 38, 38);
      }
    </style>
        <div class="capture_1" id="capture_1">
            1
            <div class="capture_2" id="capture_2">
              2
              <div class="capture_3" id="capture_3">
                3
                <div class="capture_4" id="capture_4">4</div>
              </div>
            </div>
          </div>
    <script>
      var fang1 = document.getElementById("capture_1");
      var fang2 = document.getElementById("capture_2");
      var fang3 = document.getElementById("capture_3");
      var fang4 = document.getElementById("capture_4");

      fang1.addEventListener(
        "click",
        function (e) {
    
          console.log(1);
        },
        false
      );
      fang2.addEventListener(
        "click",
        function (e) {
    
          console.log(2);
        },
        true
      );
      fang3.addEventListener(
        "click",
        function (e) {
    
          console.log(3);
        },
        false
      );
      fang4.addEventListener(
        "click",
        function (e) {
    
          console.log(4);
        },
        true
      );
    </script>
  </body>
</html>

在这里插入图片描述

一、知识点2:

༼ つ ◕_◕ ༽つJS中表单操作

表单使用

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    * {
    
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    .container {
    
      width: 800px;
      background-color: #fff;
      margin: 0 auto;
      padding-top: 100px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    #task-form {
    
      width: 100%;
    }
    .input-filter {
    
      width: 100%;
      height: 35px;
      padding-left: 10px;
      border: none;
      border-bottom: 1px solid rgb(150, 149, 149);
    }
    input:focus {
    
      outline: none;
    }
    li {
    
      list-style: none;
      padding: 5px 0;
      border-bottom: 1px solid #ededed;
    }
    .body-content {
    
      width: 100%;
      margin-top: 20px;
    }
    ul {
    
      margin-top: 20px;
      width: 100%;
    }
    a {
    
      padding-left: 20px;
      color: #039ed6;
      text-decoration: none;
      padding-top: 5px;
    }
    h5 {
    
      padding: 5px 10px;
    }
    .collection-item {
    
      display: none;
    }
    .btn {
    
      width: 100px;
      height: 30px;
      background-color: #269b91;
      border: none;
      border-radius: 2px;
      color: #fff;
    }
    .btn_2 {
    
      border: none;
      border-radius: 2px;
      height: 30px;
      color: #fff;
      background-color: #000000;
      width: 120px;
    }
  </style>
  <body>
    <div>
      <div class="container">
        <h2>Task List</h2>
        <form action="" id="task-form">
          <input
            type="text"
            class="input-filter"
            id="newTask_1"
            placeholder="New Task"
          />
          <div class="body-content">
            <input type="submit" class="btn" id="addBtn" value="Add Task" />
          </div>
        </form>
      </div>
      <div class="container">
        <h2>Tasks</h2>
        <input
          type="text"
          class="input-filter"
          id="newTask_2"
          placeholder="Filter Task"
        />
        <ul id="collection"></ul>
        <div class="body-content">
          <button id="clearBtn" class="btn_2">CLRER TASKS</button>
        </div>
      </div>
    </div>
    <script>
      //选择生成新标签输入框
      const newTask = document.getElementById("newTask_1");
      const addBtn = document.getElementById("addBtn");
      const collection = document.querySelector("#collection");
      const clearBtn = document.getElementById("clearBtn");
      const from = document.querySelector("#task-form");
      from.addEventListener("submit", function (e) {
    
        e.preventDefault();
          if (newTask.value == "" || newTask.value.length == 0) {
    
            alert("Please input search term!");
          } else {
    
            const li = document.createElement("li");
            li.className = "delect-item seondary-content";
            li.innerText = newTask.value;
            collection.appendChild(li, document.create);
          }
      });
    </script>
  </body>
</html>

在这里插入图片描述

多选、多选框中的全选

// 实现全选操作
            function checkBoxselect(){
    
                var fav=document.getElementsByName("fav");
                for(var i=0;i<fav.length;i++){
    
                        fav[i].checked=true;
                }
            }

多选、多选框中的反选

// 实现反选操作
            function checkBoxchange(){
    
                var fav=document.getElementsByName("fav");
                for(var i=0;i<fav.length;i++){
       //=是赋值符==和===才是判断符
                    if(fav[i].checked){
    
                        fav[i].checked=false;
                    }else{
    
                        fav[i].checked=true;
                    }
                }
            }

选中当前ul里面当前的点击的li

  collection.addEventListener("click",function (e) {
    
        console.log(e.target)
      })

在这里插入图片描述

表单操作

<html>
    <head>
        <title>form表单操作</title>
        <meta charset="UTF-8"/>
        <script type="text/javascript">
            function testForm(){
    
// 获取form对象 方法一,通过id,比较普遍的方法
                var fm=document.getElementById("fm");
                alert(fm);    //输出fm的类型[object HTMLFormElement]
                alert(fm.length);  //输出所用的表单项(表单类型参考Lgin.html)输出值为8
            }
            function testOper(){
    
                var fm=document.getElementById("fm");
// 输出表单的元素
// alert(fm.elements); //显示表单元素的类型[object HTMLFormControlsCollection]
// alert(fm.elements.length); //显示表单元素的个数
// 利用表单的action属性进行访问地址的动态改变
                fm.action="http://www.baidu.com";
                alert(fm.action);       //返回了action的值
// 利用表单的submit属性使普通的按钮也具有提交功能
// fm.submit(); //可以直接访问修改后的网址
// alert(fm.submit()); //执行了submit操作并且返回了undefined
            }

            function testCheck(){
    
// 获取checkbox的对象
                var fav=document.getElementsByName("fav");//通过Id无法获取,但是通过Name
// 实现选中遍历打印操作
                for(var i=0;i<fav.length;i++){
    
                    if(fav[i].checked){
    
                        alert(fav[i].value);   //其中fav没有值,但是fav.value有值,无法打印fav,但是可以打印fav.value
                    }
                }
            }
// 实现全选操作
            function checkBoxselect(){
    
                var fav=document.getElementsByName("fav");
                for(var i=0;i<fav.length;i++){
    
                        fav[i].checked=true;
                }
            }
// 实现清空选择操作
            function checkBoxclear(){
    
                var fav=document.getElementsByName("fav");
                for(var i=0;i<fav.length;i++){
    
                    fav[i].checked=false;
                }
            }
// 实现反选操作
            function checkBoxchange(){
    
                var fav=document.getElementsByName("fav");
                for(var i=0;i<fav.length;i++){
       //=是赋值符==和===才是判断符
                    if(fav[i].checked){
    
                        fav[i].checked=false;
                    }else{
    
                        fav[i].checked=true;
                    }
                }
            }
            function selectoper(){
    
// 获取单选框对象
                var sel=document.getElementById("Animation");
// 获取单选框内的选项
                var os=sel.options;
                for(var i=0;i<os.length;i++){
    
                    if(os[i].selected){
    
                        alert(os[i].value+":"+os[i].text);
                    }
                }
            }
        </script>
    </head>
    <body>
        <h3>form表单操作</h3>
        <!--添加readonly表示标签只能读,添加disabled标签表示该标签不能进行任何操作-->
        <input type="button" name="" id="" value="测试form表单" onclick="testForm()" />
        <input type="button" name="" id="" value="测试form表单基本操作" onclick="testOper()" />
        <input type="button" name="" id="" value="测试form表单checkbox" onclick="testCheck()" />
        <input type="button" name="" id="" value="测试form表单checkbox全择" onclick="checkBoxselect()" />
        <input type="button" name="" id="" value="测试form表单checkbox清空选择" onclick="checkBoxclear()" />
        <input type="button" name="" id="" value="测试form表单checkbox反选" onclick="checkBoxchange()" />
        <input type="button" name="" id="" value="测试form表单select操作" onclick="selectoper()" />
        <hr />
        <form action="#" method="get" id="fm" name="frm" target="_blank">
            <b>用户名</b><input type="text" name="wd" id="" value="" disabled="disabled" /><br /><br />
            &nbsp;&nbsp;&nbsp;<b>密码</b><input type="password" name="pwd" id="" value="" readonly="readonly"/><br />
            <br />
            爱好 <br />
            动漫<input type="checkbox" name="fav" id="fav" value="动漫" checked="false"/><br />
            游戏<input type="checkbox" name="fav" id="fav" value="游戏" checked="false"/><br />
            电影<input type="checkbox" name="fav" id="fav" value="电影" checked=""true/><br />
            敲代码<input type="checkbox" name="fav" id="fav" value="敲代码" checked="false"/><br />
            <br /><br />
            <select name="" id="Animation">
                <option value="">1</option>
                <option value="">2</option>
                <option value="">3</option>
                <option value="">4</option>
            </select>
            <br /><br />
            <input type="submit" name="" id="" value="登录" />
        </form>
    </body>
</html>

单任务和多任务删除

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    * {
    
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    .container {
    
      width: 800px;
      background-color: #fff;
      margin: 0 auto;
      padding-top: 100px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    #task-form {
    
      width: 100%;
    }
    .input-filter {
    
      width: 100%;
      height: 35px;
      padding-left: 10px;
      border: none;
      border-bottom: 1px solid rgb(150, 149, 149);
    }
    input:focus {
    
      outline: none;
    }
    li {
    
      list-style: none;
      padding: 5px 0;
      border-bottom: 1px solid #ededed;
    }
    .body-content {
    
      width: 100%;
      margin-top: 20px;
    }
    ul {
    
      margin-top: 20px;
      width: 100%;
      position: relative;;
    }
    a {
    
      padding-left: 20px;
      color: #039ed6;
      text-decoration: none;
      padding-top: 5px;
    }
    h5 {
    
      padding: 5px 10px;
    }
    .collection-item {
    
      display: none;
    }
    .btn {
    
      width: 100px;
      height: 30px;
      background-color: #269b91;
      border: none;
      border-radius: 2px;
      color: #fff;
    }
    .btn_2 {
    
      border: none;
      border-radius: 2px;
      height: 30px;
      color: #fff;
      background-color: #000000;
      width: 120px;
    }
    .fa{
    
      position: absolute;
      right: 20px;
      width: 40px;
      color: rgb(255, 0, 0);
    }
  </style>
  <body>
    <div>
      <div class="container">
        <h2>Task List</h2>
        <form action="" id="task-form">
          <input
            type="text"
            class="input-filter"
            id="newTask_1"
            placeholder="New Task"
          />
          <div class="body-content">
            <input type="submit" class="btn" id="addBtn" value="Add Task" />
          </div>
        </form>
      </div>
      <div class="container">
        <h2>Tasks</h2>
        <input
          type="text"
          class="input-filter"
          id="newTask_2"
          placeholder="Filter Task"
        />
        <ul id="collection"></ul>
        <div class="body-content">
          <button id="clearBtn" class="btn_2">CLRER TASKS</button>
        </div>
      </div>
    </div>
    <script>
      //选择生成新标签输入框
      const newTask = document.getElementById("newTask_1");
      const addBtn = document.getElementById("addBtn");
      const collection = document.querySelector("#collection");
      const clearBtn = document.getElementById("clearBtn");
      const from = document.querySelector("#task-form");
      from.addEventListener("submit", function (e) {
    
        e.preventDefault();
          if (newTask.value == "" || newTask.value.length == 0) {
    
            alert("Please input search term!");
          } else {
    
            const li = document.createElement("li");
            li.innerText = newTask.value;
            //创建a标签样式
            const link = document.createElement("a");
            //添加字体图标
            link.innerHTML = '<i class="fa fa-times">X</i>';
            //添加a标签类名
            link.className = "delect-item seondary-content";
            //将a标签插入到ul中
            li.appendChild(link);
            //将li插入到ul中
             collection.appendChild(li);
          }
      });
      //
      collection.addEventListener("click",function (e) {
    
        console.log(e.target)
       if(e.target.parentElement.classList.contains("delect-item")){
    
         e.target.parentElement.parentElement.remove();
       }
      });
      //清除任务按钮
      clearBtn.addEventListener("click", function (e) {
    
        //判断任务表中是否有任务
        if (collection.getElementsByTagName("li").length > 0) {
    
          //方法一
          // collection.innerHTML = "";
          //方法二
          while(collection.firstChild){
    
            collection.removeChild(collection.firstChild)
          }
        } else {
    
          alert("暂存任务为0,请添加任务");
        }
      });
    </script>
  </body>
</html>

本地存储

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    * {
    
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
    .container {
    
      width: 800px;
      background-color: #fff;
      margin: 0 auto;
      padding-top: 100px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    #task-form {
    
      width: 100%;
    }
    .input-filter {
    
      width: 100%;
      height: 35px;
      padding-left: 10px;
      border: none;
      border-bottom: 1px solid rgb(150, 149, 149);
    }
    input:focus {
    
      outline: none;
    }
    li {
    
      list-style: none;
      padding: 5px 0;
      border-bottom: 1px solid #ededed;
    }
    .body-content {
    
      width: 100%;
      margin-top: 20px;
    }
    ul {
    
      margin-top: 20px;
      width: 100%;
      position: relative;
    }
    a {
    
      padding-left: 20px;
      color: #039ed6;
      text-decoration: none;
      padding-top: 5px;
    }
    h5 {
    
      padding: 5px 10px;
    }
    .collection-item {
    
      display: none;
    }
    .btn {
    
      width: 100px;
      height: 30px;
      background-color: #269b91;
      border: none;
      border-radius: 2px;
      color: #fff;
    }
    .btn_2 {
    
      border: none;
      border-radius: 2px;
      height: 30px;
      color: #fff;
      background-color: #000000;
      width: 120px;
    }
    .fa {
    
      position: absolute;
      right: 20px;
      width: 40px;
      color: rgb(255, 0, 0);
    }
  </style>
  <body>
    <div>
      <div class="container">
        <h2>Task List</h2>
        <form action="" id="task-form">
          <input
            type="text"
            class="input-filter"
            id="newTask_1"
            placeholder="New Task"
          />
          <div class="body-content">
            <input type="submit" class="btn" id="addBtn" value="Add Task" />
          </div>
        </form>
      </div>
      <div class="container">
        <h2>Tasks</h2>
        <input
          type="text"
          class="input-filter"
          id="newTask_2"
          placeholder="Filter Task"
        />
        <ul id="collection"></ul>
        <div class="body-content">
          <button id="clearBtn" class="btn_2">CLRER TASKS</button>
        </div>
      </div>
    </div>
    <script>
      //选择生成新标签输入框
      const newTask = document.getElementById("newTask_1");
      const addBtn = document.getElementById("addBtn");
      const collection = document.querySelector("#collection");
      const clearBtn = document.getElementById("clearBtn");
      const from = document.querySelector("#task-form");
      //将本地任务添加到本地缓存
      from.addEventListener("submit", function (e) {
    
        e.preventDefault();
        if (newTask.value == "" || newTask.value.length == 0) {
    
          alert("Please input search term!");
        } else {
    
          const li = document.createElement("li");
          li.innerText = newTask.value;
          //创建a标签样式
          const link = document.createElement("a");
          //添加字体图标
          link.innerHTML = '<i class="fa fa-times">X</i>';
          //添加a标签类名
          link.className = "delect-item seondary-content";
          //将a标签插入到ul中
          li.appendChild(link);
          //将li插入到ul中
          collection.appendChild(li);
          storeTaskInLocalStorage(newTask.value);
        }
      });

      //dom加载数完毕执行
      document.addEventListener("DOMContentLoaded", function (e) {
    
        let tasks;
        if (localStorage.getItem("tasks") == null) {
    
          tasks = [];
        } else {
    
          tasks = JSON.parse(localStorage.getItem("tasks"));
          console.log(tasks);
          tasks.forEach(function (task) {
    
            const li = document.createElement("li");
            li.innerText = task;
            //创建a标签样式
            const link = document.createElement("a");
            //添加字体图标
            link.innerHTML = '<i class="fa fa-times">X</i>';
            //添加a标签类名
            link.className = "delect-item seondary-content";
            //将a标签插入到ul中
            li.appendChild(link);
            //将li插入到ul中
            collection.appendChild(li);
          });
        }
      });

      collection.addEventListener("click", function (e) {
    
        console.log(e.target);
        if (e.target.parentElement.classList.contains("delect-item")) {
    
          e.target.parentElement.parentElement.remove();
        }
      });
      //清除任务按钮
      clearBtn.addEventListener("click", function (e) {
    
        //判断任务表中是否有任务
        if (collection.getElementsByTagName("li").length > 0) {
    
          //方法一
          // collection.innerHTML = "";
          //方法二
          while (collection.firstChild) {
    
            collection.removeChild(collection.firstChild);
          }
        } else {
    
          alert("暂存任务为0,请添加任务");
        }
        localStorage.clear();
      });
      //filter
      function filterTask(e) {
    
        const text = e.target.value.toLowerCase();
        document.querySelector(".collection").forEach(function (e) {
    
          const item = e.firstChild.textContent;
          if (item.toLowerCase().indexOf(text) != -1) {
    
            e.style.display = "block";
          } else {
    
            e.style.display = "none";
          }
        });
      }
      //storeTaskInLocalStorage
      function storeTaskInLocalStorage(task) {
    
        let tasks;
        if (localStorage.getItem("tasks") == null) {
    
          tasks = [];
        } else {
    
          //从缓存中拿出来的是Json数据要进行解析
          tasks = JSON.parse(localStorage.getItem("tasks"));
        }
        //将新的数据加入到缓存中
        tasks.push(task);
        //将数组存储在本地,将字符串数据转化成json数据
        localStorage.setItem("tasks", JSON.stringify(tasks));
      }
      //removeTaskLocalStorage
      // function removeTaskLocalStorage(taskItem){
    
      // let tasks;
      // if(localStorage.getItem("tasks") == null){
    
      // tasks = [];
      // }else{
    
      // //从缓存中拿出来的是Json数据要进行解析
      // tasks = JSON.parse(localStorage.getItem("tasks"));
      // }
      // tasks.forEach(function(task,index){
    

      // if(task === taskItem){
    
      // console.log(taskItem)
      // //从index位置删除生成新数组
      // tasks.splice(index,1)
      // console.log(tasks)
      // localStorage.setItem("tasks",JSON.stringify(tasks));
      // }
      // })
      // }
    </script>
  </body>
</html>

原网站

版权声明
本文为[可可鸭~]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_43547255/article/details/126222910