gpt4 book ai didi

jQuery 事件触发器 - 可取消事件

转载 作者:行者123 更新时间:2023-12-01 01:16:28 25 4
gpt4 key购买 nike

我创建了一个触发事件的 jquery 插件:

$.fn.myplugin = function(options) {
this.on("foo.myplugin", options.foo);
this.on("bar.myplugin", options.bar);
};

我想检查 foo 是否已被用户取消并防止 bar 被触发:

// trigger foo
this.trigger("foo.myplugin");

// how do I check if foo was canceled
if( !fooCanceled ) {
this.trigger("bar.myplugin");
}

如何检查 foo 是否被取消以防止触发 bar?

jQuery UI 做了类似的事情,但当我尝试时它不起作用:

if (this._trigger("search", event) === false) {
return;
}

我尝试了类似的方法:

if( this.trigger("foo.myplugin") === false ) {
return;
}

this.trigger("bar.myplugin");

但是栏仍然被触发。

我正在像这样初始化我的插件:

$("#asdf").myplugin({
foo: function(event) {
// cancel the event
event.preventDefault();
},

bar: function(event) {
console.log("should not be triggered");
}
});

最佳答案

遵循此模式可能会让您实现您所追求的目标。

示例: http://jsfiddle.net/VzzLf/3/

JS

//Plugin structure from : http://docs.jquery.com/Plugins/Authoring
(function( $ ){

var methods = {
init : function( options ) {

return this.each(function(){
var ele = $(this);

ele.on('click.myPlugin', function(e){

//Hold a reference to the event
var event = $.Event("closing")

//Trigger it on the element
ele.trigger(event);

//Check to see if it was disabled
if(!event.isDefaultPrevented()){
ele.trigger('close');
}

});

});

}
};

$.fn.myPlugin = function( method ) {

if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.myPlugin' );
}

};

})( jQuery );

$(function(){
$('#myPlugin')
.myPlugin()
.on('closing', function(){
alert('closing');
})
.on('close', function(){
alert('close fired');
});
$('#myPluginDisabled')
.myPlugin()
.on('closing', function(e){
alert('Disable close');
e.preventDefault();
})
.on('close', function(e){
alert('Will never get here');
});
});

HTML

<div id='myPlugin'>Click me I'm enabled</div>

<div id='myPluginDisabled'>Click me I'm disabled</div>​

关于jQuery 事件触发器 - 可取消事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13937930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com