为什么$(window).load()工作但不是$(document).ready()? [英] Why does $(window).load() work but not $(document).ready()?
问题描述
我正在使用rails 3应用程序,我想使用可排序列表。我正在使用此处显示的方法。我的应用程序使用JQuery,我的应用程序布局中包含一个js文件,调用 $(document).ready()
来设置一些可视化内容。这似乎工作正常。
I'm working with a rails 3 app, and I want to use a sortable list. I'm working with the method shown here. My app uses JQuery, and there's a js file included in my app's layout that calls $(document).ready()
to set up some visual stuff. That seems to be working fine.
然而,当我尝试调用 $(文件).ready()
在我的视图模板中通过 content_for:javascript
设置可排序列表,该代码永远不会触发。我的布局文件中有必要的 yield:javascript
调用,如果我加载页面并查看源代码,一切看起来都很好。但代码永远不会运行 - 例如 $(document).ready()
的实例永远不会触发。
However, when I attempt to call $(document).ready()
in my view template via content_for :javascript
to set up the sortable list, that code never fires. I do have the requisite yield :javascript
call in my layout file, and if I load the page and look at the source everything looks fine. The code never runs, though – i.e. this instance of $(document).ready()
never fires.
我刚刚发现,如果我用 $(窗口)替换
然后我的js代码运行。 $(document).ready()
.load()
I've just found that if I replace $(document).ready()
with $(window).load()
then my js code runs.
所以我的问题是:为什么 $(文件).ready()
失败并且 $(窗口).load()
工作?
So my question is: Why would $(document).ready()
fail and $(window).load()
work?
这有效:
<% content_for :javascript do %>
<script>
$(window).load(function(){
alert('it works!');
});
</script>
<% end %>
这不起作用
<% content_for :javascript do %>
<script>
$(document).ready(function(){
alert('it works!');
});
</script>
<% end %>
这是布局
<!DOCTYPE html>
<html>
<head>
<title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<!-- Reset Stylesheet -->
<%= stylesheet_link_tag "reset" %>
<!-- Main Stylesheet -->
<%= stylesheet_link_tag "style" %>
<!-- Invalid Stylesheet -->
<%= stylesheet_link_tag "invalid" %>
<%= javascript_include_tag :defaults, "nested_form", "DD_belatedPNG_0.0.7a", "simpla.jquery.configuration", "facebox", "jquery-ui.min" %>
<%= yield :javascript %>
<%= yield(:head) %>
<%= csrf_meta_tag %>
</head>
<body onload="initialize()"><div id="body-wrapper">
…
推荐答案
与正文 onready =
回调已注册。请参阅jquery文档。您必须删除< body onload =initialize()>
。
There is a conflict with the body's onready=
callback registered. See the jquery docs. You must remove the <body onload="initialize()">
.
另外一种可能性是资源被非常缓慢地加载。但是第一个更有可能。
Also a possibility is a resource being loaded very VERY slowly. However the first is more likely.
.ready
在加载资源时触发。资源可能永远处于等待状态,因为服务器在将资源发送到浏览器时从不关闭套接字。使用firebug的网络监控工具来追踪是否是这种情况。
.ready
is triggered when resources are loaded. It is possible a resource may be perpetually in a wait state because the server never closed the socket when sending the resource to the browser. Use firebug's network monitor tool to track down if this is the case.
这篇关于为什么$(window).load()工作但不是$(document).ready()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!