文档加载后加载单个变量
我希望有人能在这里帮助我。我在加载此变量时遇到问题。现在,我有一个在文档准备好时显示的图像。它有一个 id。所以我试图捕获该 id 并提醒它,但是当我尝试使用 .attr() 时,它给了我未定义的变量。然而,当我执行完全相同的脚本时,在另一个窗口加载下,第一个警报给我未定义,第二个警报给我正确的 ID。
我的脚本:
window.onload = function() { //first onload gives undefined
var imgID = $('.selector').attr('id');
alert(imgID);
};
$(document).ready(function(){ //gives me correct id
var imgID = $('.selector').attr('id');
alert(imgID);
});
这两个函数放置在同一页面内。因此,当第一个警报弹出时,它会给页面加载时间,然后弹出第二个警报来捕获图像 ID。
所以我想我是想在页面加载后获取 id 吗?有人可以帮助我如何做到这一点吗?谢谢
I hope someone can help me here. I'm having trouble loading this variable. Right now I have an image that is being displayed when the document is ready. It has an id to it. So I'm trying to capture that id and alert it, but when I tried using .attr(), it gives me undefined variable. However, when I do the exact same script, under another window load, the first alert gives me undefined, the second gives me the correct id.
My Script :
window.onload = function() { //first onload gives undefined
var imgID = $('.selector').attr('id');
alert(imgID);
};
$(document).ready(function(){ //gives me correct id
var imgID = $('.selector').attr('id');
alert(imgID);
});
These two functions are placed inside same page. So when the first alert pops up, it gives the page time to load and then second alert pops up which captures the image id.
So I guess I'm trying to get the id after the page is loaded? Can someone help me on how to do that? Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了做我想做的事,我只需要设定时间间隔。
To do what I wanted to accomplish, I just had to set time interval.
即使没有 window.onload 存在, document.ready 也应该可以工作。顺便说一句,您可以使用 jQuery 的
$()
缩写来表示 document.ready:The document.ready should work even without window.onload being there. BTW, you can use jQuery's
$()
abbreviation for document.ready:$(document).ready 在这里应该足够了,因为该函数在 DOM 加载后启动。你说它对你有用,所以我不明白问题是什么。您可以删除 window.onload 并使用 $(document).ready。
http://www.learningjquery.com/2006/09/introducing-document-ready
$(document).ready should be sufficient here as the function starts once DOM has been loaded. You say it works for you so I don't see what the problem is. You can remove the window.onload and use $(document).ready.
http://www.learningjquery.com/2006/09/introducing-document-ready