如何等待,直到图像加载在jquery

How to wait until image is loaded in jquery

本文关键字:图像 加载 jquery 何等待 等待      更新时间:2023-09-26

我有这个例子,当我的表单提交时,我必须加载一个图像文件,直到图像加载到return 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

这里必须注意一个重要的概念—当您添加一个事件处理程序函数以在触发特定事件时执行时,事件处理程序函数return s的值实际上不存在,而是传递给任何东西。事件监听器的创建是为了在未来的未知点调用事件处理函数,但是典型的脚本执行是完全线性的,并且按照脚本中命令的顺序发生——因此最好以一种方式定义应用程序的功能,即仅在某些事件发生时执行某些操作。

看起来在上面的问题中,您定义了一个事件处理程序来侦听表单最初提交的时间,所以我将把它作为启动一切的初始事件。以下是我将如何处理你所描述的提交过程:

//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/

祝你好运!

您可以在图像上使用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事件。如果您愿意,您仍然可以使用提交,它可能仍然可以工作,只要您返回false或使用preventDefault

我使用的是imagesLoaded v3.1.8

你可以在github上找到:https://github.com/desandro/imagesloaded

他们的官方网站:http://imagesloaded.desandro.com/