jQuery - wait for user input
I'm experiencing quire a nasty problem. Here it goes:
My script uploads file(s) and responds back with a JSON encoded object, which contains file ID numbers that need additional information.
Now, the problem. I'd like to display a dialog (a form) and wait for user to fill it, send it via AJAX back to server, and then repeat the same process for the second ID number, and so on.
I tried to do this using $.each, but unsuccessfully. I read $.each can be terminated by returning false in callback f开发者_如何学JAVAunction, but I did not find anything mentioning how to wait for an event (let's say submit button in my form to be clicked) and then continuing the loop.
Nice day
Solution:
coll_id = 0; // collection pointer
collection = [
{
id : 4,
fileName : 'somefile.mp3'
},
{
id : 6,
fileName : 'anotherFile.mp3'
}
];
function openDialog(){
$('#browser-add-files-id3').bind('dialogclose', function(){
if(coll_id >= collection.length-1){
try{
closeDialog(collection[coll_id].id);
}
catch(err){
}
coll_id++;
}
else {
closeDialog(collection[coll_id].id);
coll_id++;
openDialog();
}
});
$('#id3-file').text(collection[coll_id].fileName);
$('#browser-add-files-id3').dialog('open');
}
function closeDialog(mid){
// $.post to /url/param/mid
// cleanup the input fileds in dialog
}
You can not mix asynchronous behavior with .each() which is synchronous. What you could do is loop over all items with .each(), and check if you find one that hasn't been processed. If so you mark it as processed, fire the asynchronous request, and then return false to stop each().
In the asynchronous success callback, you just trigger the .each() loop again, it will skip all processed items, and if one is found that hasn't been processed, mark it as such and start the async request, etc.
For marking items as processed, I'd recommend using $(item).data('processed', true)
or anything alike using jQuery's data function.
精彩评论