JS 增删留言案例

HTML部分

<body>
		<div id="box">
			<input type="text" name="" id="inpu" value="" />
			<button type="button">发送</button>
			<ul id="leave">

			</ul>
		</div>
	</body>

JS部分

<script type="text/javascript">
		var inpval = document.querySelector('#inpu')
		var ul = document.querySelector('ul')
		var bu = document.querySelector('button')
		bu.addEventListener('click', function() {
			var trufal = nul()
			//判断输入是否为空
			if (trufal != true) {
				return alert('您输入为空')
			}
			//调用时间函数
			var thistime = gettime()
			var valuee = inpval.value
			//创建盒子容器
			var li = document.createElement('li')
			ul.appendChild(li)
			//创建头像
			var imgsrc = document.createElement('img')
			imgsrc.src = 'img/人.jpg'
			li.appendChild(imgsrc)
			//创建内容
			var tex = document.createElement('div')
			tex.className = 'tex'
			var timerl = document.createElement('p')
			var textv = document.createElement('p')
			tex.appendChild(timerl)
			//写入内容 时间
			timerl.innerText = thistime
			tex.appendChild(textv)
			//写入内容
			textv.innerText = valuee
			li.appendChild(tex)

			var del = document.createElement('a')
			del.innerText = '删除'
			//删除事件
			del.onclick = function() {
				li.remove()
			}
			//添加页面元素

			if (ul.children.length == 0) {
				li.insertBefore(del)
			} else {
				li.appendChild(del)
			}
			inpval.value = ''

		})
		function gettime() {
			var tim = new Date
			var year = tim.getFullYear() //年
			var month = tim.getMonth() + 1 //月
			var day = tim.getDate() //日
			var h = tim.getHours() //小时
			var min = tim.getMinutes() //分
			return year + '年' + month + '月' + day + '日' + h + '时' + min + '分'
		}

		function nul() {
			//清楚空格
			var valuee = inpval.value.trim()
			//判断是否输入了
			if (valuee.length == 0) {
				return false
			} else {
				return true
			}
		}
	</script>

效果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值