example12.html 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 type="text" name="fruit">
  62. <input id="ok" type="button" value="确定">
  63. </div>
  64. <script src="js/jquery.min.js"></script>
  65. <script>
  66. // 写JavaScript代码时为什么推荐使用jQuery而不写原生JavaScript
  67. // 因为jQuery对象有更多的属性和方法, 能够用更少的代码做更多的事情
  68. // 而且jQuery对象的方法使用灵活且没有浏览器兼容性问题
  69. // 当加载jQuery成功时会在window对象上绑定名为jQuery的属性
  70. // 该属性还有一个名字叫$, $既是一个对象也是一个函数
  71. // 当$作为函数时有以下四种最常用的用法:
  72. // 1. 如果$函数的参数是一个函数, 传入的函数是页面加载完成时要执行的回调函数
  73. // 2. 如果$函数的参数是选择器字符串, 那么$函数会返回代表元素的jQuery对象(其本质是一个数组)
  74. // 3. 如果$函数的参数是标签字符串, 那么$函数会创建该标签并返回对应的jQuery对象
  75. // 4. 如果$函数的参数是原生JavaScript对象(DOM), 那么$函数将该对象处理成jQuery对象
  76. // 用法1
  77. $(function() {
  78. function removeItem(evt) {
  79. evt.preventDefault();
  80. // 用法4
  81. $(evt.target).parent().remove();
  82. }
  83. function addItem(evt) {
  84. // 用法2
  85. var fruitName = $("#fruits+input").val().trim();
  86. if (fruitName.length > 0) {
  87. // 用法3
  88. var $li = $("<li>").text(fruitName);
  89. // 用法3
  90. var $a = $("<a href=''>").text("×").on("click", removeItem);
  91. $("#fruits").append($li.append($a));
  92. }
  93. $("#fruits+input").val("");
  94. $("#fruits+input").focus();
  95. }
  96. // 用法2
  97. $("#fruits a").on("click", removeItem);
  98. $("#ok").on("click", addItem);
  99. });
  100. </script>
  101. </body>
  102. </html>