没有得到变量值?

Shi*_*idi 0 jquery

我没有在加载函数中获得"img_srt"变量的值,任何身体都可以帮助我吗?

$(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);
}
Run Code Online (Sandbox Code Playgroud)

str*_*ger 5

设置的函数img_srt是异步调用的.也就是说,它可以在您的alert陈述之前或之后执行.可能之后,因为你有这个问题.

尝试这样的事情:

$('<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');
        }
    });
Run Code Online (Sandbox Code Playgroud)