如何在jQuery中等待图像加载完成

4

我有一个例子,当我的表单被提交时,我必须加载一个图片文件并等待图片加载完毕才能返回true(在这种情况下是提交表单)。

例如:

$('#myform').submit(function(){
  var image=document.createElement('image')  
  var src=document.createAttribute('src')
  image.value="http://example.com/image.jpg"
  image.setAttributeNode(src);
  document.body.appendChild(image);
})

在这里,如果我return true,表单就会被提交(图片不会加载),如果是false,就不会提交(图片会加载但表单不会提交)。如何编写代码,在图片加载后返回true呢?


3
请查看jQuery插件:waitForImages - mutil
3个回答

3
这里有一个重要的概念需要注意 - 当您添加一个事件处理函数来执行特定事件时,事件处理函数返回的值实际上不会传递到任何地方。事件监听器被创建用于在未知的将来某个时间点调用事件处理函数,但典型的脚本执行是完全线性的,并按照脚本中命令的顺序进行 - 因此最好以这种方式定义应用程序的功能,当发生某些事件时才执行某些操作。
从您上面的问题看,您正在定义一个事件处理程序来监听表单最初提交的事件,因此我将其视为启动整个过程的初始事件。以下是我处理您描述的提交过程的方法:
//wrap the form element in jQuery and cache it so we don't work to re-select it
var $myform = $('#myform');

//specify that we are listening for -when- the form is submit
$myform.on('submit', function(event){
    //prevents the form from actually submitting when submit is first clicked
    event.preventDefault();

    //Simpler image construction
    var image = new Image();
    document.body.appendChild(image);

    //remember to listen for the image's load event before assigning a source
    $(image).on('load', function(){
        //this function is invoked in the future,
        //when the image load event has been fired

        //this bit actually submits the form via GET or POST
        $myform.submit();
    });

    //an image's `src` attribute can be set directly via the`src` property
    image.src = "http://placekitten.com/320/240";
});

下面是JSFiddle上工作的示例:

http://jsfiddle.net/Admiral/uweLe/

我建议您学习jQuery的.on()方法,了解当前首选的事件绑定方法 - 这应该会让事情变得更加清晰明了。

http://api.jquery.com/on/

祝你好运!


2
您可以在图像上使用 onloadjquery load 事件,并在回调函数中提交表单。然后,如果您想要更长时间的等待,还可以在回调函数中添加超时。

类似于:

$('#myform .submitButton').click(function(e){
  e.preventDefault();

  var image=document.createElement('image');

  $(image).load(function(){

    //Submits form immediately after image loaded.
    $('#myForm').submit();  

    // Submits form 1 second after image has loaded
    setTimeout(function(){ $('#myForm').submit(); }, 1000); 
  });

  var src=document.createAttribute('src');
  image.value="http://example.com/image.jpg";
  image.setAttributeNode(src);
  document.body.appendChild(image);
})

注意:在我的示例中,我将submit事件更改为click事件。如果您愿意,仍然可以使用submit,只要您返回false或使用preventDefault,它可能仍然有效。


使用 src.value 而不是 Image.value?除此之外,最好的答案比 Admiral Potato 更好,因为它可以循环。 - Raoul Mensink

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接