如何创建一个JavaScript侦听器函数,当条件为true时将执行操作? [英] How do I create a javascript listener function that will perform an action when a condition is true?
问题描述
我正在使用第三方javascript,这使我非常需要侦听器.例如,当某个div已加载时,我想对其进行处理.它会同时改变对象的样式,因此我需要注意它是否具有某种样式.我已经建立了在存在ID或类时执行操作的函数.这是当前的ID功能.如您所见,它使用jQuery.
I'm using a third party javascript that has given me a lot of need for listeners. For instance, when a certain div has been loaded, I want to do something with it. It changes styles of objects as it goes as well so I need to watch for it to have a certain style. I've build functions to act when an id or class exists. Here's the current ID function. As you can see, it uses jQuery.
function whenLoaded(element_id, action) {
if ($(element_id)) {
action();
}
else {
setTimeout("whenLoaded('"+element_ids+"',"+action+", '"+stop_on+"')", 500);
}
}
我真的需要一些可以赋予多个条件的东西.例如:
I really need something that I can give multiple conditions to. For instance:
whenTrue(
($('popup') && $('popup').style.width == '500px'),
$('popup').style.width = '0'
);
我希望它可以递归检查条件(第一个参数).当这些条件成立时,请执行操作.
I would expect it to recursively check the conditions (1st param). When those conditions are true, perform the action.
我已经能够使用eval()完成此操作,但已警告我不要使用它,不记得为什么.话虽这么说,我想以另一种方式来做到这一点.
I've been able to accomplish this using eval() but I have been warned not to use it, can't remember why. That being said, I'd like to accomplish this in another way.
eval()解决方案:
eval() solution:
whenTrue(
"($('popup') && $('popup').style.width == '500px')",
"$('popup').style.width = '0'"
);
function whenTrue(condition, action) {
if (eval(condition)) {
eval(action);
}
else {
setTimeout("whenTrue('"+condition+"','"+action+"')", 500);
}
}
推荐答案
function conditionListener(callback){
if(typeof callback !== 'function') return;
var interval, callback = callback;
interval = setInterval(function() {
if(true /* some condition */){
callback();
clearInterval(interval);
}
}, 500);
}
var listener = new conditionListener(function() {
/* ... do work ... */
});
这篇关于如何创建一个JavaScript侦听器函数,当条件为true时将执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!