如何在使用JQuery加载图像后运行代码

时间:2015-08-04 20:46:46

标签: javascript jquery html

我只是在加载了img元素之后才尝试加载元素,但我已经尝试了所有我能想到的东西而且没有任何工作。现在我正在尝试查看代码停止工作的位置,我发现我设置的警报在我需要执行代码的行之后没有运行。

#STOP LOOPS
RewriteCond %{REQUEST_URI} ^/(stats/|missing\.html|failed_auth\.html|error/).* [NC]
RewriteRule .* - [L]

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

$ img在函数中定义。警报适用于document.ready行,但不适用于$img = $('#picture'); function bubbleOnLoad() { $(document).ready(function() { $img.load(function(){ alert('document loaded') $('#left-bubble').show(); }) }) 之后。我试图添加eventlisteners,jquery .on,.load和其他一些。我也调用函数在我的init函数中运行。有人能解释为什么没有什么工作吗?

$img.load

4 个答案:

答案 0 :(得分:4)

您的代码中存在一些语法错误,我已经纠正并提出了这个错误:

function bubbleOnLoad() {
    $img = $('#picture');
    $img.load(function () {
        alert('document loaded');
        $('#left-bubble').show();
    });
}

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

Here is the JSFiddle demo

答案 1 :(得分:1)

在您的代码中,您甚至不会告诉浏览器它应该在图像加载后运行代码。你应该做这样的事情:

$(function(){

  // DOM Content is ready, let's interact with it.

  $('#picture').attr('src', 'image.jpg').load(function() {  
    // run code
    alert('Image Loaded');  
  });

});

同样according to docs开发人员尝试使用.load()快捷方式解决的常见挑战是在图像(或图像集合)完全加载时执行函数。应该注意有几个已知的警告。这些是:

  • 它不能始终如一地工作,也不能可靠地跨浏览器
  • 如果图像src设置为与之前相同的src,它在WebKit中无法正确触发
  • 它没有正确地冒泡DOM树 可以停止触发已经存在于浏览器缓存中的图像

答案 2 :(得分:1)

试试这个jQuery插件 waitForImages

https://github.com/alexanderdickson/waitForImages

//Javascript/jQuery
$(document).ready(function(){
  var counter = 0,totalImages= $('#preloader').find('img').length; 
  $('#preloader').find('img').waitForImages(function() {
    //fires for all images waiting for the last one.
    if (++counter == totalImages) {
      $('#preloader').hide();
      yourCallBack();
    }
  });
});
/*css*/
#preloader{
  position:absolute;
  top:-100px;/*dont put in DOM*/
}

#preloader > img{
  width:1px;
  height:1px;
}
<!--HTML [add the plugin after jQuery] -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.waitforimages/1.5.0/jquery.waitforimages.min.js" ></script>
 

<!--HTML [after body start] -->
<div id=preloader>
  <img src="1.jpg" />
  <img src="2.jpg" />
  <img src="3.png" />
  <img src="4.gif" />
  <img src="5.jpg" />
</div>

答案 3 :(得分:0)

您只能在DOM中创建HTML元素后才能访问它 您还需要在显示之前检查图像是否已加载 因此,您的代码需要看起来如下:

$(document).ready(function() {
    bubbleOnLoad(); 
});
      
function bubbleOnLoad() {
    var newSrc = "https://lh5.googleusercontent.com/-lFNPp0DRjgY/AAAAAAAAAAI/AAAAAAAAAD8/Fi3WUhXGOY0/photo.jpg?sz=328";
    $img = $('#picture');
    $img.attr('src', newSrc) //Set the source so it begins fetching
      .each(function() {
          if(this.complete) {
            alert('image loaded')
            $('#left-bubble').show();
          }
      });
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left-bubble" style="display:none">
  <img id="picture"/>
</div>

相关问题