[英]how to listen for two events and only fire one function in jquery mobile?
[英]Javascript listen two events and fire one function
如何检测两个不同的事件,并且只有在检测到所有两个事件时才会触发一个函数?
创建此功能:
var got = { first : 0, second : 0 };
function fire(event_type)
{
got[ event_type ] = 1;
if( got.first && got.second )
{
//do stuff and reset
got = { first : 0, second : 0 };
}
}
这是听众的一部分:
document.onclick=function (){fire('first');}
document.onmouseover=function (){fire('second');}
这是Promises擅长的地方:
var prom1 = new Promise(function(resolve, reject){
$("foo").one("someEvent", resolve);
});
var prom2 = new Promise(function(resolve, reject){
$("bar").one("otherEvent", resolve);
});
Promise.all([prom1, prom2]).then(function(){
//woo!
});
检测它们,在收到它们时进行记录,并检查是否已收到另一个(这意味着已收到)。 当发生这种情况时,请记住“忘记”它们。
你有很多选择。
例如:(不使用任何库)
(function(){
a=false; b=false;
function doIt(){
alert('both function have fired')
}
document.onclick=function (){a=true;if(a&&b) doIt()}
document.onmouseout=function (){b=true;if(a&&b) doIt()}
})()
JsFiddle: http : //jsfiddle.net/3nDds/您需要在文档中单击,然后移出文档。
另一种选择是使用data属性。
$("#mybutton").on("mouseover", function(event) {
var $button = $(this);
$button.data("mouse", true);
dowork($button);
}).on("click", function(event) {
var $button = $(this);
$button.data("click", true);
dowork($button);
});
function dowork($button)
{
if($button.data("mouse") == true && $button.data("click") == true) {
alert('both events');
$button.data('mouse', false).data('click', false);
}
}
如果是两个状态,则在第一个事件侦听器之后将函数调用放在彼此内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.