jquery – Not getting a variable value? – Education Career Blog

I am not getting the value of the variable of “img_srt” in load function, can any body helps me?

$(document).ready(function() {
    Get_var();
})

var img_srt='<div>address</div>';   

function Get_var() {
    $("<img />").attr("src","http://www.google.com/intl/en_ALL/images/logo.gif")
        .load(function() {
            if (this.height > 0) {
                img_srt += "<div><img src='http://www.google.com/intl/en_ALL/images/logo.gif'/></div>";         
            }
        })
    alert(img_srt);
}

,

The function which sets img_srt is called asynchronously. That is, it may be executed before or after your alert statement. Likely after, as you’re having this problem.

Try something like this:

$('<img/>')
    .attr('src', 'http://www.google.com/intl/en_ALL/images/logo.gif')
    .load(function() {
        var imageLoaded = this.height > 0;

        if(imageLoaded) {
            $(this).appendTo('#myDiv');
        } else {
            $('<p/>').text('Unable to load image').appendTo('#myDiv');
        }
    });

Leave a Comment