当我把jquery库放在body之前时$(document).ready不工作

时间:2013-10-11 20:02:27

标签: javascript jquery optimization

正在运作

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").slideToggle();
  });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button>Toggle between slide up and slide down for a p element</button>

</body>
</html>

但是当我搬家时

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

<body>标签之前它不起作用,因为我想把JavaScript放在底部,但是我不能把文件.ready部分放在jquery库之后,什么是解决方案。

2 个答案:

答案 0 :(得分:4)

一:你的代码 必须 来到jquery库之后。

二:如果您将代码移到页面底部,则不需要$(document).ready(...

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>This is a paragraph.</p>
<button>Toggle between slide up and slide down for a p element</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("button").click(function(){
  $("p").slideToggle();
});
</script>
</body>
</html>

如果绝对必须在jquery库上面包含特定于页面的代码,那么您可能需要一个队列系统,以便在jquery可用时,将处理该队列。以下是一个例子

<!DOCTYPE html>
<html>

    <head>
        <!-- this would need to be part of the CMS header -->
        <script>
            window.initQueue = [];
        </script>

        <!-- here's your page specific js -->
        <script>
            window.initQueue.push(function(){
                $("button").click(function() {
                    $("p").slideToggle();
                });
            })
        </script>
    </head>

    <body>
        <p>This is a paragraph.</p>
        <button>Toggle between slide up and slide down for a p element</button>


        <!-- cms footer -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            $.each(window.initQueue,function(i,fn){
                fn();
            })
        </script>
    </body>
</html>

答案 1 :(得分:2)

<script>
  window.onload = function() {
    $("button").click(function() {
       $("p").slideToggle();
    });
}

</script>