example10.html 2.4 KB

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