$(document).ready在我将jquery库放在body之前时不起作用

$(document).ready is not working when i put jquery library before body

本文关键字:body 不起作用 document ready jquery      更新时间:2023-09-26

它正在工作

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

第一:你的代码必须出现在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>
<script>
  window.onload = function() {
    $("button").click(function() {
       $("p").slideToggle();
    });
}
</script>