js使用DOM操作實現簡單留言板的方法

來源:互聯網
上載者:User

js使用DOM操作實現簡單留言板的方法

 簡易留言板,也就是自娛自樂版,說白了就是練習DOM操作。

要點一:document.createElement("標籤名") 建立元素

要點二:父元素.appendChild("元素") 把建立的元素插入到頁面的標籤中(在標籤的最後一個顯示),這樣才會在瀏覽器中顯示出來

要點三:父元素.insertBefore("元素","要插入哪個元素的前面") 把建立的元素插入到頁面中指定的標籤前面,這樣後面輸入的內容才會顯示到前面

要點四:父元素.removeChild("元素") 刪除指定元素

下面,上代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>無標題文檔</title>

<script>

window.onload = function(){

var oMsg = document.getElementById("msg");

var oBtn = document.getElementById("btn");

var oMsg_c = document.getElementById("msg_c");

var oUl = document.createElement("ul");

oMsg_c.appendChild(oUl);

oBtn.onclick = function(){

var sVal = oMsg.value;

var oli = document.createElement("li");

oli.innerHTML = sVal + " <span>刪除</span>";

var oli1 = oUl.getElementsByTagName("li");

if(oli1.length>0){

oUl.insertBefore(oli,oli1[0]);

}else{

oUl.appendChild(oli);

}

oMsg.value='';

var oSpan = document.getElementsByTagName("span");

for(var i=0; i<oSpan.length; i++){

oSpan[i].onclick = function(){

oUl.removeChild(this.parentNode);

}

}

}

}

</script>

</head>

<body>

<h1>簡易留言板</h1>

<input id="msg" type="text" size="40" value="">

<input id="btn" type="button" value="留言">

<div id="msg_c"></div>

</body>

</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.