gpt4 book ai didi

javascript - 实现一个遍历数组的运行器

转载 作者:行者123 更新时间:2023-11-29 22:24:11 25 4
gpt4 key购买 nike

BOLD 表示更新。

我有一个数组,steps,其内容是具有 Action 的对象和与之关联的元素。像这样:

steps = [{action: 'click', element: <jQuery element>}, 
{action: 'click', element: <jQuery element>}, ., ., N]

我想实现一个运行器,它的工作是遍历数组中的每个元素并对元素执行特定的操作。每个步骤必须连续执行。例如,如果您有:

 steps = [{action: 'click', element: <jQuery element representing a button>},
{action: 'click', element: <jQuery element representing an anchor tag>}]

Running,run(steps, timeout),会跑完每一步。 step[0].action 将在 step[0].element 上执行。由于 step[0] 可以创建要在 step[1] 中与之交互的 dom 元素(通过 AJAX),因此 runner 需要等待特定时间段(因此,超时), 轮询 dom 是否存在 step[1].element.

这是我目前所掌握的粗略内容:

var run = function() { 
$.each(steps, function(i, v) {
var interval = 25,
start = 0,
timeout = 3000;
var i = setInterval(function(timeout) {
start = start + interval;
console.log(start);
if ($(v).is(':visible')) {
v.click();
console.log('clicked', v);
clearInterval(i);
}
}, interval);
});
};

请注意,在上面的示例中,steps 只是一个 jquery 对象数组。它还不是所需的格式:

steps = [{action: 'click', element: <jQuery element>}, 
{action: 'click', element: <jQuery element>}, ., ., N]

可以说,我需要遵循的“模式”是什么?我是否需要使用延迟对象来处理这个问题?是用setTimeout、setInterval实现的吗?谢谢!

最终实现

var run = function(steps, interval, timeout) {
var timer,
time = 0,
i = 0;

runSingle(steps[0]);

function abort() {
console.log("Run aborted");
}

function runSingle(step) {
timer = setInterval(function() {
time += interval;
if ($(step.element).is(':visible') === true) {
clearInterval(timer);
time = 0;
$(step.element).trigger(step.action);
(i < (steps.length - 1)) && runSingle(steps[++i]);
} else if (time >= timeout) {
clearInterval(timer);
abort();
}
}, interval);
console.log("Performed: ", step.action, "on", step.element)
if (i === (steps.length - 1)) console.log("Run successful");
}
}

最佳答案

这里有一些东西。我还没有彻底测试它:

var run = function(steps, interval)
{
var timer,
time = 0, timeout = 10000,
ciel = steps.length - 1,
i = 0;

run_single(steps[0]);

function run_single(item)
{
timer = setInterval(function()
{
var $el = $(item.selector);

time += interval;

if ( $el.length )
{
clearInterval( timer );
time = 0;

$el.trigger( item.action );

i < ciel && run_single( step[ ++i ] );
}
else
{
if ( time >= timeout ) clearInterval( timer );
}

}, interval);
}
};

var steps = [
{action: 'click', selector: '#first'},
{action: 'hover', selector: '#second'},
{action: 'change', selector: '#third'}
// and so on...
];

run(steps, 100);

在此处查看实际效果:http://jsfiddle.net/myaeh/

关于javascript - 实现一个遍历数组的运行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10592666/

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