简体   繁体   中英

how do you create a function to load an image per demand

JavaScript to source and load the image:

<script>

function heat_map_load() {
    var heat_map="http://example.com/login.png";
    $(document).ready(function(){

        var myImage = new Image();
        $(myImage).load(function () {

            $('#login img').css({ "width": "auto", "height": "auto" });

        }).error(function () {
            $('#login').hide();
        }).attr('src', heat_map)
    });
}
</script>

html:

<a class="profile" style="width: 100px;" id="web_login_p" href="#" data-chart="line" data-range="1m">heat map</a>


<div class="main" id="login" style="width:700px; height:300px;"></div>

JavaScript to load the image per click:

$("#web_login_p").click(function() {
    heat_map_load();
});

when I click the web_login_p, I get heat_map_load not defined error. Any ideas what I am missing here?

heat_map_load is not defined because it is visible only in local scope, which is document.ready handler. Benjamin is right, you should move the click handler in .ready . Here is working example:

$(document).ready(function(){
    var heat_map = "http://www.google.com/images/srpr/logo11w.png";
    function heat_map_load() {

        var myImage = new Image();
        $('#login').append($(myImage));
        $(myImage).load(function () {

            $('#login img').css({ "width": "auto", "height": "auto" });


        }).error(function () {
            $('#login').hide();
        }).attr('src', heat_map);

    }
    $("#web_login_p").click(function() {
        heat_map_load();
    });
});

http://jsfiddle.net/mnTyG/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM