批改狀態(tài):合格
老師批語(yǔ):想法不錯(cuò), 加一個(gè)時(shí)間
留言板執(zhí)行順序:
1、獲取留言文本內(nèi)容->2、獲取留言列表UL->3、留言板添加事件監(jiān)聽(tīng)(用keypress鍵盤(pán)事件->UL內(nèi)添加li元素和button元素->對(duì)li賦值->將留言?xún)?nèi)容顯示并最新留言置頂)->4、添加刪除事件(引用事件代理)。
學(xué)習(xí)到的新函數(shù):
createElement() 創(chuàng)建元素 appendChild() 添加元素 removeChild() 刪除元素 childElementCount() 獲取子元素?cái)?shù)量
insertBefor() 插入節(jié)點(diǎn) confirm() 插入彈窗
以下是例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>留言板案例</title> <style> textarea{margin-bottom: 40px;} ul{padding: 0;margin: 0;} ul li{list-style: none;margin: 10px;font-size: 20px;} </style> </head> <body> <h2>留言板:</h2> <textarea name="" rows="10" maxlength="" cols="70" autofocus id="textarea"></textarea> <ul id="ul"></ul> <script> var date = new Date();//獲取時(shí)間戳 var year=date.getFullYear(); //獲取當(dāng)前年份 var mon=date.getMonth()+1; //獲取當(dāng)前月份 var da=date.getDate(); //獲取當(dāng)前日 var h=date.getHours(); //獲取小時(shí) var m=date.getMinutes(); //獲取分鐘 var s=date.getSeconds(); //獲取秒 var time = year+'-'+mon+'-'+da+' '+h+':'+m+':'+s;//拼接時(shí)間格式 //獲取文本域 var textarea = document.getElementById('textarea'); //獲取UL列表 var ul = document.getElementById('ul'); //添加監(jiān)聽(tīng)事件 textarea.addEventListener('keypress',liuyan,false); function liuyan(event){ //當(dāng)按下Enter鍵觸發(fā)事件 if (event.key === 'Enter') { if (textarea.value == '') { alert('請(qǐng)輸入內(nèi)容'); }else{ var li = document.createElement('li');//創(chuàng)建li元素 li.innerHTML = '<span style="color:#4876FF;">peter zhu :</span> '+textarea.value+' '+'<span style="font-size:16px;color:#ccc">'+time+'</span>'+' <button style="color:red;">刪除</button>';//對(duì)li進(jìn)行賦值,并添加刪除標(biāo)簽 //將li以最新時(shí)間順序添加顯示在頁(yè)面 if (ul.childElementCount === 0) { ul.appendChild(li); }else{ ul.insertBefore(li,ul.firstElementChild); } textarea.value = null;//將文本域清空 } } //應(yīng)用事件代理原理添加刪除事件 ul.addEventListener('click',del,false); function del(event){ if (confirm('是否刪除')) { var ull = event.currentTarget;//事件添加者 var btn = event.target;//事件的觸發(fā)者 var lii = btn.parentElement;//觸發(fā)者的父元素 console.log(btn,lii,ull); ull.removeChild(lii); } } } </script> </body> </html>
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)