问题
I'm trying to trigger a second event dependent on the first like so:
...
$('#productFamilyId').val(data.contents.productfamily);
$('#productFamilyId').trigger('change', function() {
$('#productId').val(data.contents.product);
$('#productId').trigger('change');
});
It's not waiting for the first trigger to complete before attempting to trigger the second event. Is it possible to wait for the first trigger to complete?
回答1:
There is no callback for the trigger method. The extra parameters are just that - parameters.
http://api.jquery.com/trigger/
What you're actually doing is running the code in the second function and then passing the result as a parameter into the event handler called by trigger. You need to trigger the 2nd event within the event handler for the first event if you want them to run in sequence.
回答2:
Probably you want this:
$('#productFamilyId').trigger('change', function() {
$('#productId').val(data.contents.product);
setTimeout(function(){
$('#productId').trigger('change');
},1);
});
回答3:
you can use javascripts setTimeout() function, so that the function will execute after some interval.
$('#productFamilyId').val(data.contents.productfamily);
$('#productFamilyId').trigger('change', function() {
setTimeout( function(){
$('#productId').val(data.contents.product);
$('#productId').trigger('change');
},100);
});
回答4:
If your event handler doesn't execute a asynchronous call, the triggered event will execute and finish, only then will go to the next line. JsFiddle
$('#productFamilyId').val(data.contents.productfamily);
$('#productFamilyId').trigger('change');
// Execute after change complete
$('#productId').val(data.contents.product);
$('#productId').trigger('change');
With asynchronous call (setTimeOut, Ajax etc) in the event handler you can do this: JsFiddle
Add a callback function as parameter in your event handler:
$("#productFamilyId").change(function(e, callback) {
// Simulating ajax
setTimeout(function() {
if (typeof callback === "function")
callback();
}, 3000);
});
And trigger like this:
$('#productFamilyId').trigger('change', function() {
$('#productId').val(data.contents.product);
$('#productId').trigger('change');
});
来源:https://stackoverflow.com/questions/11564494/how-do-i-detect-a-jquery-trigger-events-completion