问题描述
我有这个例子,当我提交表单时,我必须加载一个图像文件并等到图像加载到返回true
(在这种情况下提交表格)
I have this example, when my form is submitted I have to load an image file and wait until the image has loaded to return true
(in this case to submit the form)
例如
$('#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);
})
如果我返回true
此表格将被提交(图片将不会加载),如果 false
它不会(图片将加载,但不会提交表格)。如何创建一个在图像加载后返回true的代码。
Here if I return true
the form will be submitted (the image won't load) and if false
it won't (the image will load but the form will not be submitted). How can I make a code that will return true after the image has loaded.
推荐答案
这里必须注意一个重要的概念 - 当您添加要在特定事件触发时执行的事件处理程序函数时,事件处理程序函数返回
的值实际上无处可去,并且传递给任何内容。创建事件监听器以在将来的未知点调用事件处理程序函数,但典型的脚本执行完全是线性的,并且按照脚本中命令的顺序发生 - 因此最好以某种方式定义应用程序的功能只有当某些事件发生时才会执行这样的某些操作。
There is an important concept one must note here - When you add an Event Handler function to be executed when a particular event is fired, the value that the Event Handler function return
s actually goes nowhere, and is passed to nothing. Event Listeners are created to invoke Event Handler functions at an unknown point in the future, but typical script execution is completely linear and happens in the order of the commands in the script - so it is best to define the functionality of your application in a way that you perform certain actions like this only when certain events take place.
在上面的问题中,您正在定义一个事件处理程序来监听表单时最初提交,所以我将把它作为初始事件,让一切都开始。以下是我将如何处理您描述的提交过程:
It looks like in your question above, you are defining one event handler to listen for when the form is submitted initially, so I will take that as the initial event which gets everything started. Here is how I would handle the submission process you describe:
//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起作用的例子:
Example of this working on JSFiddle:
我建议阅读jQuery的 .on()
方法,以获得对当前首选的事件绑定方法的一些见解 - 这应该可以清除位。
I would recommend reading up on jQuery's .on()
method to gain some insight on the currently preferred methods of event binding - that should clear things up a bit.
祝你好运!
这篇关于如何等待图像加载到jquery中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!