当我将 jquery 库放在正文之前时,$(document).ready 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19326317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$(document).ready is not working when i put jquery library before body
提问by Parnit Das
It is working
这是工作
<!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>
But when i move
但是当我移动
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Before <body>
tag is it is not working, because i want Put JavaScript at bottom, but i can't put document.ready part after jquery library, what will be solution.
在<body>
标记之前它不起作用,因为我想把 JavaScript 放在底部,但是我不能把 document.ready 部分放在 jquery 库之后,有什么解决方案。
采纳答案by Nanhe Kumar
<script>
window.onload = function() {
$("button").click(function() {
$("p").slideToggle();
});
}
</script>
回答by Kevin B
One: your code MUSTcome after the jquery library.
一:您的代码必须在 jquery 库之后。
Two: If your moving the code to the bottom of the page, you don't need $(document).ready(...
.
二:如果您将代码移动到页面底部,则不需要$(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>
If you absolutely must have your page specific code above the jquery library, you'll likely need a queue system so that when jquery is available, the queue will be processed. Below is an example
如果您绝对必须将页面特定代码放在 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>