开发者

loading a single variable after document loads

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


To do what I wanted to accomplish, I just had to set time interval.


The document.ready should work even without window.onload being there. BTW, you can use jQuery's $() abbreviation for document.ready:

$(function() {
    var imgID = $('.selector').attr('id');
    alert(imgID);
});


$(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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜