在 上使用 jquery document.ready()事件
我有以下需求:我想在每次页面加载图像时调用js,但是 我还需要在js运行之前完成页面的DOM加载。
我写了下面的“虚拟”示例,我想知道它是否可以被认为是正确的。 它似乎有效,但是,因为 jquery 说:“.ready() 方法通常与 属性”,我希望有人告诉我:“是的,你可以做到这一点”。
非常感谢您的帮助, 尼科
示例:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function mySetVal() {
$(document).ready(function () {
$("#status").val("Refreshing");
});
}
</script>
</head>
<body>
<div style="border:1px solid green">
<img src="target.jpeg" id="cat" onload="mySetVal()"></img>
</div>
<div>
<p>E poi che la sua mano a la mia puose con lieto volto, ond'io mi confortai, mi mise dentro a le segrete cose.</p>
</div>
<table>
<tr>
<th>animale</th><th>pianta</th>
</tr>
<tr>
<td>mucca</td><td>palma</td>
</tr>
</table>
<p>Input: <input type="text" id="status" /></p>
</body>
</html>
I have the following need: I want to call a js each time an image is loaded on the page but
I also need that the DOM of the page is completed loaded before the js runs.
I wrote the following 'dummy' example and I would like to know if it can be considered correct or not.
It seems to work but, since jquery says: "The .ready() method is generally incompatible with the
attribute", I would like someone to tell me: "yes, you can do that".
Thanks a lot for your help,
Nico
Example:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function mySetVal() {
$(document).ready(function () {
$("#status").val("Refreshing");
});
}
</script>
</head>
<body>
<div style="border:1px solid green">
<img src="target.jpeg" id="cat" onload="mySetVal()"></img>
</div>
<div>
<p>E poi che la sua mano a la mia puose con lieto volto, ond'io mi confortai, mi mise dentro a le segrete cose.</p>
</div>
<table>
<tr>
<th>animale</th><th>pianta</th>
</tr>
<tr>
<td>mucca</td><td>palma</td>
</tr>
</table>
<p>Input: <input type="text" id="status" /></p>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你可以这样做,只要 jQuery 在图像之前加载,因为如果调用时 DOM 已经准备好,那么将直接调用
ready
函数。Yes you can do that, as long as jQuery is loaded before the image, since the
ready
function will be called directly if the DOM is already ready when it is called.是的,这正是 $(document)ready(...) 的含义。
查看 http://docs.jquery.com/Tutorials:Introducing_$%28document%29。 Ready%28%29
“一旦加载 DOM,并且在加载页面内容之前,其中的所有内容都会加载”
Yes it is exactly what $(document)ready(...) was meant for.
Look at http://docs.jquery.com/Tutorials:Introducing_$%28document%29.ready%28%29
"Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded"
我建议您从 img 标签中删除内联属性 onload 。
您可以使用此代码:
I suggest you to remove the inline attribute onload from img tag.
You can use this code: