example_of_jquery_2.html 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #fruits {
  12. width: 120px;
  13. margin: 20px 20px;
  14. }
  15. #fruits>li {
  16. list-style-type: none;
  17. height: 40px;
  18. color: white;
  19. background-color: #009966;
  20. line-height: 40px;
  21. text-align: center;
  22. margin-top: 2px;
  23. }
  24. #fruits>li>a {
  25. float: right;
  26. color: white;
  27. text-decoration: none;
  28. }
  29. #fruits~input {
  30. border: none;
  31. outline: none;
  32. text-align: center;
  33. margin: 20px 15px;
  34. }
  35. input[type=text] {
  36. border-bottom: 1px solid gray !important;
  37. }
  38. #ok {
  39. width: 80px;
  40. height: 30px;
  41. background-color: #CC3333;
  42. color: white;
  43. }
  44. </style>
  45. </head>
  46. <body>
  47. <div id="container">
  48. <ul id="fruits">
  49. <li>苹果<a href="">×</a></li>
  50. <li>香蕉<a href="">×</a></li>
  51. <li>火龙果<a href="">×</a></li>
  52. <li>西瓜<a href="">×</a></li>
  53. </ul>
  54. <input type="text" name="fruit">
  55. <input id="ok" type="button" value="确定">
  56. </div>
  57. <script src="js/jquery.min.js"></script>
  58. <script>
  59. function removeListItem(evt) {
  60. evt.preventDefault()
  61. // $函数的参数是一个原生的JavaScript对象,返回与原生JavaScript对象对应的jQuery对象
  62. $(evt.target).parent().remove()
  63. }
  64. // $函数的四种用法:
  65. // $函数的参数是一个匿名函数或箭头函数,传入的函数是页面加载完成后要执行的回调函数
  66. $(() => {
  67. // $函数的参数是一个样式表选择器字符串,获取页面元素得到一个jQuery对象(伪数组 - 数组中装的是原生JavaScript对象)
  68. $('#fruits>li>a').on('click', removeListItem)
  69. $('#ok').on('click', (evt) => {
  70. let input = $('#ok').prev();
  71. let name = input.val().trim()
  72. if (name) {
  73. $('#fruits').append(
  74. // $函数的参数是一个标签字符串,创建一个新的元素并获得对应的jQuery对象
  75. $('<li>').text(name).append(
  76. $('<a href="">').html('&times;').on('click', removeListItem)
  77. )
  78. )
  79. }
  80. input.val('').get(0).focus()
  81. })
  82. })
  83. </script>
  84. </body>
  85. </html>