用于获取和加载图像的 JavaScript:
<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:
$("#web_login_p").click(function() {
heat_map_load();
});
当我点击 web_login_p 时,出现 heat_map_load not defined 错误。有什么想法我在这里遗漏了什么吗?
最佳答案
heat_map_load
未定义,因为它仅在本地范围内可见,即 document.ready
处理程序。
Benjamin 是对的,您应该在 .ready
中移动点击处理程序。这是工作示例:
$(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();
});
});
关于javascript - 你如何创建一个函数来按需加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20550511/