setTimeout没有在我的Tampermonkey脚本中使用jQuery等待?

时间:2014-11-29 21:32:08

标签: jquery for-loop settimeout greasemonkey tampermonkey

我试图在Tampermonkey中执行一个脚本,它会点击包含来自不同设计师的项目的网页上的复选框标签。我有两个独立的数组中的男/女设计师,然后合并数组。

我根据页面上的复选框输入检查数组,然后单击每个相应的设计器复选框。由于这会执行AJAX调用,因此有时会在单击所有项目时终止页面。我希望在循环的每次迭代之前等待500毫秒。但是,setTimeout似乎不起作用 - 它在页面加载后单击所有按钮并完全忽略超时。

我读过有一个jQuery等待函数:
$(allDesigners).each().wait(500, {function(){}});
但这只是导致一个未定义的函数错误,也不起作用。

任何有关添加超时或简化代码的建议,提示或提示都会很棒!

// ==UserScript==
// @name     Click Specified Designers
// @require  http://code.jquery.com/jquery-1.9.1.js
// @grant    GM_addStyle
// @run-at document-end
// ==/UserScript==
/*- The @grant directive is needed to work around a major design
change introduced in GM 1.0.
It restores the sandbox.
*/
$(document).ready(function(){
var womenDesigners = ["127","132","223","2709","267","286","296","260","531","815","842","860","938","1081","1361","1415"];
var mensDesigners  = ["84","128","131","224","2218","268","380","297","530","544","579","814","843","861","1080","1104","1362","1401","1416"];
var allDesigners   = $.merge( $.merge( [], womenDesigners ), mensDesigners );

$.each(allDesigners, function(i, val) {
$("input[type=checkbox]").each(function(){
  var inputValue = $(this).attr("value");     
    if(inputValue == val) {   
        setTimeout(function() {
            $(this).parent().click();
        }, 500);
        }                
    });

});

1 个答案:

答案 0 :(得分:2)

this丢失了范围,因此在setTimeout $(this)内调用this表示作为setTimeout回调传递的匿名函数。

之前保存范围。

$("input[type=checkbox]").each(function(){
  var self = $(this);
  var inputValue = self.attr("value");

    if(inputValue == val) {   
        setTimeout(function() {
            self.parent().click();
        }, 500);
    }                
});

此外,.each循环是一个同步循环,所有setTimeout s将同时设置,所有500ms将在setTimeout之后触发。你需要一个递归循环链.each()

另一件事是您不需要CSS复选框,您可以直接使用$.each(allDesigners, function(i, val) { var el = $("input[type=checkbox][val=" + val + "]"); setTimeout(function() { el.parent().click(); }, 500 * i); }); 选择器:

{{1}}