Javascript 在jQuery中:如何触发自定义延迟事件
我有一个这样的插件:Javascript 在jQuery中:如何触发自定义延迟事件,javascript,jquery,jquery-plugins,jquery-deferred,Javascript,Jquery,Jquery Plugins,Jquery Deferred,我有一个这样的插件: (function($){ $.fn.extend({ myplugin: function () { var jobs = []; this.each(function(){ jobs.push($(this).one( 'load', function(){ // Line A: "Load" fires here // Repla
(function($){
$.fn.extend({
myplugin: function () {
var jobs = [];
this.each(function(){
jobs.push($(this).one(
'load',
function(){
// Line A: "Load" fires here
// Replace image source
$(this).attr('src','new_url');
// Line B: Everything is done, fire now!
}));
});
// Callback
$.when.apply(null,jobs).then(function(){
alert($(this).attr('src'));
});
return this;
}
});
})(jQuery);
“when”帮助程序始终提醒旧图像源。因为它是在A行加载后调用的。但我需要在B行启动它
如何解决这个问题?有什么想法吗
谢谢大家! 你不会把任何尊重传递给什么时候。您传递的只是一个jQuery对象数组 为集合中的每个项创建一个新项,然后在事件侦听器中创建它:
(function($){
$.fn.myplugin = function () {
var deferreds = [];
this.each(function() {
var deferred = $.Deferred();
deferreds.push(deferred);
$(this).one('load', function() {
this.src = 'new_url';
deferred.resolve();
});
});
$.when.apply($, deferreds).then(function() {
alert('All sources have been changed.');
});
return this;
};
})(jQuery);
为了更简洁,您可以将函数传递给延迟构造函数:
this.each(function (i, element) {
deferreds.push( $.Deferred(function (deferred) {
$(element).one('load', function() {
this.src = 'new_url';
deferred.resolve();
});
}));
});
你没有把任何尊重传递给什么时候。您传递的只是一个jQuery对象数组 为集合中的每个项创建一个新项,然后在事件侦听器中创建它:
(function($){
$.fn.myplugin = function () {
var deferreds = [];
this.each(function() {
var deferred = $.Deferred();
deferreds.push(deferred);
$(this).one('load', function() {
this.src = 'new_url';
deferred.resolve();
});
});
$.when.apply($, deferreds).then(function() {
alert('All sources have been changed.');
});
return this;
};
})(jQuery);
为了更简洁,您可以将函数传递给延迟构造函数:
this.each(function (i, element) {
deferreds.push( $.Deferred(function (deferred) {
$(element).one('load', function() {
this.src = 'new_url';
deferred.resolve();
});
}));
});
我对延迟对象很陌生,但这是我如何使用的一个很好的例子!非常感谢。我对延迟对象很陌生,但这是我如何使用的一个很好的例子!非常感谢。