js 留言板(帶刪除功能)


 

本文所用的知識點:創建節點和添加節點

創建節點:document.createElement('li')

添加節點  node(父親節點).appendChild(child)    child:子節點   追加式添加元素
 
insertBefore:使得插入的元素始終顯示在最前面
 
 

 

 

 

 

<!-- 
 * @Author: panda 
 * @Date: 2020-06-15 21:00:37 
 * @Last Modified by:   panda
 * @Last Modified time: 2020-06-15 21:00:37 
  -->
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>刪除留言板案例</title>
  <style>
    * {
      margin:
        0;
      padding:
        0;
    }

    a {
      text-decoration: none;
      color: #333333;
    }

    a:hover {
      text-decoration: underline;
      color: #45bcf9;
    }

    .del {
      float: right;
    }

    ul,
    li {
      list-style:
        none;
    }

    .wrap {
      width:
        400px;
      margin:
        100px auto;
    }

    li {
      padding:
        5px;
      border-bottom:
        1px solid #eeeeee;
      margin: 5px 0;
      font-size: 14px;
      line-height: 28px;
    }

    button {
      background:
        #169fe6;
      border:
        none;
      color:
        #ffffff;
      padding:
        5px 15px;
      cursor: pointer;
    }

    button:hover {
      background:
        #45bcf9;
    }

    textarea {
      width:
        100%;
      padding:
        10px;
      box-sizing:
        border-box;
    }
  </style>
</head>

<body>


  <div class="wrap">
    <div> <textarea name="" id="" cols="30" rows="10"></textarea> </div>
    <div> <button>評論</button></div>
    <ul></ul>
  </div>





  <script>
    var text = document.querySelector('textarea');
    var btn = document.querySelector('button');
    var ul = document.querySelector('ul');

    // 注冊事件
    btn.onclick = function () {
      // 判斷用戶是否輸入值
      if (text.value == '') {
        alert('請輸入評論內容!');
        return false;
      } else {
        // 1、創建節點
        var li = document.createElement('li');
        // 2、將用戶輸入的值賦添加到li元素中去,使用 innerHTML,再添加一個刪除按鈕
        li.innerHTML = text.value + '<a href = "javascript:;" class = "del">刪除</a>';
        // 3、添加節點
        ul.insertBefore(li, ul.children[0]);
        text.value = '';

        // 刪除操作  node.removeChild(child)
        var a = document.querySelectorAll('a');
        for (var i = 0; i < a.length; i++) {
          a[i].onclick = function () {
            // 刪除當前a所在的li元素
            ul.removeChild(this.parentNode);
          }
        }
      }
    }
  </script>
</body>

</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM