正在运作
<!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库之后,什么是解决方案。
答案 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>