3

这是工作

<!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 放在底部,但我不能在 jquery 库之后放置 document.ready 部分,这将是什么解决方案。

4

2 回答 2

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>
于 2013-10-11T20:08:27.437 回答
1
<script>
  window.onload = function() {
    $("button").click(function() {
       $("p").slideToggle();
    });
}

</script>
于 2013-10-11T20:10:42.067 回答