jQuery学习笔记2——温故+知新

jQuery学习笔记2——温故+知新

开始之前:http://docs.jquery.com/ 是jQuery文档的网站, https://jsfiddle.net/是js的在线验证工具。

如果你没有html,CSS,js,jQuery基础,请学习它们先。

Introduction

Web pages made withHTML andCSS display static content. They don’t respond to user actions like clicking a mouse or typing a key.

JavaScript andjQuery are used to make web pages interactive.

  • JavaScript is a programming language used to create web pages that change in response to user actions.
  • jQuery is a collection of prewritten JavaScript code that lets us easily create interactive effects on our site.
1. 介绍一个实际的例子,可以在https://jsfiddle.net/上得到验证。

这个例子是侧面菜单的点击滑入效果:

1. <html>
2. <head>
3. <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
4. <link href='http://fonts.googleapis.com/css?family=Open+Sans:400;300' rel='stylesheet' type='text/css'>
5. <link href='style.css' rel='stylesheet'>
6. 
7. 
8. </head>
9. <body>
10. 
11. <div class="menu">
12. 
13. <!-- Menu icon -->
14. <div class="icon-close">
15. <img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/uber/close.png">
16. </div>
17. 
18. <!-- Menu -->
19. <ul>
20. <li><a href="#">About</a></li>
21. <li><a href="#">Blog</a></li>
22. <li><a href="#">Help</a></li>
23. <li><a href="#">Contact</a></li>
24. </ul>
25. </div>
26. 
27. <!-- Main body -->
28. <div class="jumbotron">
29. 
30. <div class="icon-menu">
31. <i class="fa fa-bars"></i>
32. Menu
33. </div>
34. 
35. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
36. <script src="app.js"></script>
37. </body>
38. </html>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

CSS:

1. /* Initial body */
2. body {
3. left: 0;
4. margin: 0;
5. overflow: hidden;
6. position: relative;
7. }
8. 
9. /* Initial menu */
10. .menu {
11. background: #202024 url('http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/uber/black-thread.png') repeat left top;
12. left: -285px;  /* start off behind the scenes */
13. height: 100%;
14. position: fixed;
15. width: 285px;
16. }
17. 
18. /* Basic styling */
19. 
20. .jumbotron {
21. background-image: url('http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/uber/bg.png');
22. height: 100%;
23. -webkit-background-size: cover;
24. -moz-background-size: cover;
25. -o-background-size: cover;
26. background-size: cover;
27. }
28. 
29. .menu ul {
30. border-top: 1px solid #636366;
31. list-style: none;
32. margin: 0;
33. padding: 0;
34. }
35. 
36. .menu li {
37. border-bottom: 1px solid #636366;
38. font-family: 'Open Sans', sans-serif;
39. line-height: 45px;
40. padding-bottom: 3px;
41. padding-left: 20px;
42. padding-top: 3px;
43. }
44. 
45. .menu a {
46. color: #fff;
47. font-size: 15px;
48. text-decoration: none;
49. text-transform: uppercase;
50. }
51. 
52. .icon-close {
53. cursor: pointer;
54. padding-left: 10px;
55. padding-top: 10px;
56. }
57. 
58. .icon-menu {
59. color: #fff;
60. cursor: pointer;
61. font-family: 'Open Sans', sans-serif;
62. font-size: 16px;
63. padding-bottom: 25px;
64. padding-left: 25px;
65. padding-top: 25px;
66. text-decoration: none;
67. text-transform: uppercase;
68. }
69. 
70. .icon-menu i {
71. margin-right: 5px;
72. }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

js:

1. var main = function(){
2. $('.icon-menu').click(function(){
3. $('.menu').animate({left: '0px'},200);
4. $('body').animate({left: '285px'},200);
5. });
6. $('.icon-close').click(function(){
7. $('.menu').animate({left: '-285px'},200);
8. $('body').animate({left: '0px'},200);
9. });
10. };
11. 
12. $(document).ready(main);
2. 一个点击显示隐藏的下拉菜单的实例,用到.children().show();

本例中有纵向排列的4个顶级菜单,每个顶级菜单在单击时可以显示它对应的下拉详情。

html总体结构:

html代码:

1. <div class="articles container">
2. 
3. <div class="article current">
4. <div class="item row">
5. <div class="col-xs-3">
6. <p class="source">FLIGHT</p>
7. </div>
8. <div class="col-xs-6">
9. <p class="title">Embraer adds third Legacy 500 prototype to flight test campaign</p>
10. </div>
11. <div class="col-xs-3">
12. <p class="pubdate">Mar 23</p>
13. </div>
14. </div>
15. <div class="description row">
16. <div class="col-xs-3"> </div>
17. <div class="col-xs-6">
18. <h1>Embraer adds third Legacy 500 prototype to flight test campaign</h1>
19. <p>The third Legacy 500 has joined Embraer's flight test programme aimed at delivering the midsize business jet in 2014. The airtcraft, serial number 003...</p>
20. </div>
21. <div class="col-xs-3"> </div>
22. </div>
23. </div>
24. 
25. <div class="article">
26. <div class="item row">
27. <div class="col-xs-3">
28. <p class="source">AW Commercial Aviation</p>
29. </div>
30. <div class="col-xs-6">
31. <p class="title">CSeries Supplier Scramble</p>
32. </div>
33. <div class="col-xs-3">
34. <p class="pubdate">Mar 22</p>
35. </div>
36. </div>
37. <div class="description row">
38. <div class="col-xs-3"> </div>
39. <div class="col-xs-6">
40. <h1>CSeries Supplier Scramble</h1>
41. <p>Three months before the planned first flight of its CSeries, Bombardier is grappling with supplier issues crucial to meeting its production cost...</p>
42. </div>
43. <div class="col-xs-3"> </div>
44. </div>
45. </div>
46. 
47. <div class="article">
48. <div class="item row">
49. <div class="col-xs-3">
50. <p class="source">AW business aviation</p>
51. </div>
52. <div class="col-xs-6">
53. <p class="title">Flying the Gulfstream G650</p>
54. </div>
55. <div class="col-xs-3">
56. <p class="pubdate">Mar 22</p>
57. </div>
58. </div>
59. <div class="description row">
60. <div class="col-xs-3"> </div>
61. <div class="col-xs-6">
62. <h1>Flying the Gulfstream G650</h1>
63. <p>Gulfstream is turning up the heat in the large-cabin business aircraft competition with its new G650 flagship, the largest, fastest, farthest-ranging...</p>
64. </div>
65. <div class="col-xs-3"> </div>
66. </div>
67. </div>
68. <div class="item row">
69. <div class="col-xs-3">
70. <p class="source">FLIGHT</p>
71. </div>
72. <div class="col-xs-6">
73. <p class="title">New retirements cut RAF VC10 fleet to four</p>
74. </div>
75. <div class="col-xs-3">
76. <p class="pubdate">Mar 22</p>
77. </div>
78. </div>
79. <div class="description row">
80. <div class="col-xs-3"> </div>
81. <div class="col-xs-6">
82. <h1>New retirements cut RAF VC10 fleet to four</h1>
83. <p>The UK Royal Air Force has retired another two of its Vickers VC10 tankers, with the pair's departure reducing its inventory of the Rolls-Royce...</p>
84. </div>
85. <div class="col-xs-3"> </div>
86. </div>
87. </di
88. 
89. </div>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

点击.article可以显示它下面的第一个 .description 的内容,使用了.children(). js code:

1. var main = function(){
2. $('.article').click(function(){
3. $(this).children('.description').show();
4. //children() : nested directly under the current element.
5. });
6. };
7. $(document).ready(main);

后面再升级的js: 

1. var main = function(){
2. $('.article').click(function(){
3. $('.article').removeClass('current');//remove the current from all
4. $('.description').hide();//Hide the descriptions of all
5. $(this).addClass('current');//hilight the current article
6. $(this).children('.description').show();//show the description of the clicked one
7. //children() : nested directly under the current element.
8. });
9. /*Nice! Now when you click an article, it's shaded gray and its description opens up.*/
10. /*Next let's see how to add two keyboard shortcuts. Here's what we want:press o, open the article; press n, open the next article*/
11. //create a keypress event handler
12. //The event handler should take event as a parameter.
13. $(document).keypress(function(event){
14. if (event.which === 111){//pressed 'o' key
15. <span style="white-space:pre">			</span>$('.description').hide();/*Hide the descriptions of all articles*/
16. $('.current').children('.description').toggle();//open the on we clicked.
17. <span style="white-space:pre">		</span>}
18. else if (event.which === 110){
19. /*1.Select the current article using the '.current' selector. Save this in a new variable named currentArticle*/
20. var currentArticle = $('.current');
21. /*2.Select the next article using currentArticle.next(). Save this in a new variable named nextArticle*/
22. var nextArticle = currentArticle.next();
23. /*3.Remove the 'current' class from currentArticle using .removeClass()*/
24. currentArticle.removeClass('current');
25. /*4.Add the 'current' class to nextArticle using .addClass()*/
26. nextArticle.addClass('current');
27. }
28. });
29. };
30. $(document).ready(main);
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

上面这个代码作几点总结:

  • 要搞你selected的title, 先close all,再show你的那个current
  • 对current的使用,相当于一个标签,非常重要!
  • .next() 的使用方法,可参考:https://api.jquery.com/next/
  • .children() 的使用方法,非常重要
  • 最后使用了两个变量 currentArticle & nextArticle来装Object, 同时用到.next()来平移,后面的操作都是针对这两个容器来进行。
  • removeClass(‘active-slide’);  //注意这里没有**"."**

最后贴出CSS代码:

1. body {
2. background-image: url('http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/reader/bg.png');
3. -webkit-background-size: cover;
4. -moz-background-size: cover;
5. -o-background-size: cover;
6. background-size: cover;
7. }
8. 
9. p {
10. margin: 0;
11. }
12. 
13. .row {
14. margin: 0;
15. }
16. 
17. .articles {
18. margin-top: 30px;
19. margin-bottom: 30px;
20. }
21. 
22. .article {
23. color: #222;
24. background: rgba(255,255,255,.9);
25. border-spacing: 2px;
26. border-color: gray;
27. font-family: arial,sans-serif;
28. border-bottom: 1px #e5e5e5 solid;
29. }
30. 
31. .current .item {
32. background: rgba(206,220,206,.9);
33. }
34. 
35. .item {
36. cursor: pointer;
37. padding-top: 7px;
38. padding-bottom: 7px;
39. 
40. }
41. 
42. .item .source {
43. margin-left: 20px;
44. }
45. 
46. .item .title {
47. font-weight: bold;
48. }
49. 
50. .item .pubdate {
51. margin-right: 20px;
52. }
53. 
54. .item .pubdate {
55. text-align: right;
56. }
57. 
58. .description {
59. display: none;
60. padding-top: 10px;
61. padding-bottom: 10px;
62. }
63. 
64. .description h1 {
65. margin-top: 0px;
66. font-size: 23px;
67. }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
3. 关于$( )

$( )

In jQuery, we often see $( ). It has two main uses:

  • To select existing HTML elements on the page.

$('p') selects all p elements on the page.

  • To create new HTML elements to add to the page.

$('<h1>') creates a new h1 element. The < > indicates that we want to create a new HTML element.

.text()

The .text() method adds text to an HTML element.

.appendTo( )  vs .prependTo( )

The .appendTo() method adds HTML elements to the end of the selected element.

1. $('.btn').click(function() {
2. $('<li>').text('New item').appendTo('.items');
3. });
4. /**************************************/
5. $('.btn').click(function() {
6. $('<li>').text('New item').prependTo('.items');
7. });

Click the New button in the web page to the right.

The .prependTo() method adds HTML elements to the beginning of the selected element.

.remove( )

Click the Delete button in the web page to the right.
The .remove() method removes the selected HTML element from the web page.

1. $('.btn').click(function() {
2. $('.selected').remove();
3. });

.text( )

These six jQuery methods let you control more aspects of HTML elements:

  • .hide() hides the selected HTML element
  • .show() displays an element
  • .toggle() alternates hiding and showing an element
  • .addClass() adds a CSS class to an element
  • .removeClass() removes a class from an element
  • .toggleClass() alternates adding and removing a class from an element
4. -理解DOM Document Object Model

  • .next( )
  • .prev( )
  • .children( )
5. 操作elements in html

有很多操作html中elements的方法,详见:http://learn.jquery.com/using-jquery-core/manipulating-elements/
这里我们要说的是.appendTo(), 和 .prependTo()
以下代码实现的是响应 class= “btn” 的按钮的click动作,生成一个

  • element,然后用prependTo()操纵它放在 ul class = “posts"的列表里。

    1. var main = function(){
    2. $('.btn').click(function(){   //a click event handler
    3. var post;
    4. post = $('.status-box').val();//.val() is like .text() but to Get or set the value of form elements.
    5. //1. use $('<li>') to create a new li element;
    6. //2. use .text(post) to add text to the element
    7. //3. use .prependTo() to prepend it to the <ul class="posts">...</ul> element.
    8. $('<li>').text(post).prependTo('.posts');
    9. //create element -> inject text -> manipulate element
    10. });
    11. 
    12. //这里要更新剩余字数Count characters left
    13. $('.status-box').keyup(function(){ //a keyup event handler
    14. var postLength = $(this).val().length; //store the length of the massage typed in the status box.
    15. var charactersLeft = 140 - postLength;
    16. //update the '.counter' to show the left value
    17. $('.counter').text(charactersLeft);
    18. });
    19. }
    20. $(document).ready(main);
    ![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
    
  • Published At
    comments powered by Disqus