JQuery.one() 立即触发的事件
JQuery.one() event that fires immediately
我正在制作一个 jquery 插件,您可以在其中设置事件发生的事件。
$.fn.makeSomething = function(options) {
var defaults = {
activationEvent: "mouseover"
};
options = $.extend(defaults, options);
this.each(function() {
var elem = $(this);
elem.one(options.activationEvent, function(){
// some code to be called at the event (in which I use elem)
// but by default should be called immediately on load
});
});
return this;
}
我希望默认情况下它只是在没有任何必要交互的情况下发生。这可能吗?
更多信息:
我有几个 div 应该加载一些额外的内容。默认情况下,我希望在页面加载时加载内容。但是,在某些页面上,我不希望所有内容都随页面一起加载,但我希望仅当您将鼠标悬停在其 div.
上时才加载每个部分
谢谢!
如果将 function
定义与绑定分开:
$.fn.makeSomething = function(options) {
// ...
function doSomething() {
// ...
}
$(this).one(options.activationEvent, doSomething);
};
您可以测试 activationEvent
不是事件的默认值,例如 null
,为 .each()
:
提供相同的功能
$.fn.makeSomething = function(options) {
var defaults = {
activationEvent: null
};
options = $.extend(defaults, options);
function doSomething() {
var $elem = $(this);
// ...
}
if (!options.activationEvent)
this.each(doSomething);
else
this.one(options.activationEvent, doSomething);
};
// act immediately
$('...').makeSomething();
// act on mouseover
$('...').makeSomething({ activationEvent: 'mouseover' });
.one()
和 .each()
都将调用 doSomething()
,this
引用 DOM 元素。 (注意:但是,提供给 doSomething()
的参数将有所不同。)
我正在制作一个 jquery 插件,您可以在其中设置事件发生的事件。
$.fn.makeSomething = function(options) {
var defaults = {
activationEvent: "mouseover"
};
options = $.extend(defaults, options);
this.each(function() {
var elem = $(this);
elem.one(options.activationEvent, function(){
// some code to be called at the event (in which I use elem)
// but by default should be called immediately on load
});
});
return this;
}
我希望默认情况下它只是在没有任何必要交互的情况下发生。这可能吗?
更多信息:
我有几个 div 应该加载一些额外的内容。默认情况下,我希望在页面加载时加载内容。但是,在某些页面上,我不希望所有内容都随页面一起加载,但我希望仅当您将鼠标悬停在其 div.
上时才加载每个部分谢谢!
如果将 function
定义与绑定分开:
$.fn.makeSomething = function(options) {
// ...
function doSomething() {
// ...
}
$(this).one(options.activationEvent, doSomething);
};
您可以测试 activationEvent
不是事件的默认值,例如 null
,为 .each()
:
$.fn.makeSomething = function(options) {
var defaults = {
activationEvent: null
};
options = $.extend(defaults, options);
function doSomething() {
var $elem = $(this);
// ...
}
if (!options.activationEvent)
this.each(doSomething);
else
this.one(options.activationEvent, doSomething);
};
// act immediately
$('...').makeSomething();
// act on mouseover
$('...').makeSomething({ activationEvent: 'mouseover' });
.one()
和 .each()
都将调用 doSomething()
,this
引用 DOM 元素。 (注意:但是,提供给 doSomething()
的参数将有所不同。)