jQuery中的100个技巧(上)

前端 javascript ajax 1194      收藏
jQuery中的100个技巧、jQuery、jQuery常用技巧

1.当document文档就绪时执行JavaScript代码。

我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行

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

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

 

        <script>

 

            // Different ways to achieve the Document Ready event

 

            // With jQuery

            $(document).ready(function(){ /* ... */});

 

            // Short jQuery

            $(function(){ /* ... */});

 

            // Without jQuery (doesn't work in older IE versions)

            document.addEventListener('DOMContentLoaded',function(){

                // Your code goes here

            });

 

            // The Trickshot (works everywhere):

 

            r(function(){

                alert('DOM Ready!');

            })

 

            function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

 

        </script>

2.使用route。

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

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

 

        <script>

 

            var route = {

                _routes : {},    // The routes will be stored here

 

                add    : function(url, action){

                    this._routes[url] = action;

                },

 

                run : function(){

                    jQuery.each(this._routes, function(pattern){

                        if(location.href.match(pattern)){

                            // "this" points to the function to be executed

                            this();

                        }

                    });

                }

            }

 

            // Will execute only on this page:

            route.add('002.html', function(){

                alert('Hello there!'

评论
  • 贤心 VIP3 (楼主)
    2017-11-30

    香菇那个蓝瘦,这是一条被采纳的回帖

    66 回复
    编辑 删除
  • 2017-11-30

    蓝瘦那个香菇,这是一条没被采纳的回帖

    0 回复
    编辑 删除 采纳