example10.html 2.4 KB
Newer Older
骆昊的技术专栏's avatar
骆昊的技术专栏 已提交
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}
			#container {
				margin: 20px 50px;
			}
			#fruits li {
				list-style: none;
				width: 200px;
				height: 50px;
				font-size: 20px;
				line-height: 50px;
				background-color: cadetblue;
				color: white;
				text-align: center;
				margin: 2px 0;
			}
			#fruits>li>a {
				float: right;
				text-decoration: none;
				color: white;
				position: relative;
				right: 5px;
			}
			#fruits~input {
				border: none;
				outline: none;
				font-size: 18px;
			}
			#fruits~input[type=text] {
				border-bottom: 1px solid darkgray;
				width: 200px;
				height: 50px;
				text-align: center;
			}
			#fruits~input[type=button] {
				width: 80px;
				height: 30px;
				background-color: coral;
				color: white;
				vertical-align: bottom;
				cursor: pointer;
			}
		</style>
	</head>
	<body>
		<div id="container">
			<ul id="fruits">
				<li>苹果<a href="">×</a></li>
				<li>香蕉<a href="">×</a></li>
				<li>火龙果<a href="">×</a></li>
				<li>西瓜<a href="">×</a></li>
			</ul>
			<input id='name' type="text" name="fruit">
			<input id="ok" type="button" value="确定">
		</div>
		<script src="js/jquery.min.js"></script>
		<script>
			function removeItem(evt) {
				evt.preventDefault();
				// $函数的第四种用法:参数是原生的JS对象
				// 将原生的JS对象包装成对应的jQuery对象
				$(evt.target).parent().remove();
			}
			
			// $函数的第一种用法: 参数是另一个函数
			// 传入的函数是页面加载完成之后要执行的回调函数
			// $(document).ready(function() {});
			$(function() {
				// $函数的第二种用法:参数是一个选择器字符串
				// 获取元素并得到与之对应的jQuery对象(伪数组)
				$('#fruits a').on('click', removeItem);
				$('#ok').on('click', function() {
					var fruitName = $('#name').val().trim();
					if (fruitName.length > 0) {
						$('#fruits').append(
							// $函数的第三种用法:参数是一个标签字符串
							// 创建新元素并得到与之对应的jQuery对象
							$('<li>').text(fruitName).append(
								$('<a>').attr('href', '').text('×').on('click', removeItem)
							)
						);
					}
					// 对jQuery对象使用下标运算或调用get()方法会得到原生JS对象
					$('#name').val('').get(0).focus();
				});
			});
		</script>
	</body>
</html>