留言板(初學者使用js實現)


代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>留言板</title>
</head>
<body>
  <input type="text"><input type="button" value="請留言">
  <ul></ul>

  <script>
    //獲取頁面元素
    var oInp = document.querySelectorAll('input');
    var oUl = document.querySelector('ul');
    //給按鈕添加點擊事件
    oInp[1].onclick = function(){
      //獲取文本框中的內容
      var str = oInp[0].value;
      //創建li
      var oLi = document.createElement('li');
      //創建文本節點
      var oTxt = document.createTextNode(str);
      oLi.appendChild(oTxt);
      //創建a
      var oA = document.createElement('a');
      oA.href = "javascript:;"//將a作為js中的按鈕用,不再跳轉
      //設置a中的內容
      oA.innerHTML = '刪除';
      oA.onclick = function(){
        this.parentNode.parentNode.removeChild(this.parentNode);
      }
      oLi.appendChild(oA);
      if(oUl.firstChild){
        oUl.insertBefore(oLi,oUl.firstChild);
      }else{
        oUl.appendChild(oLi);
      }
    }
  </script>
</body>
</html>


免責聲明!

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



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