代码在setTimeout外部有效,但在内部无效

时间:2018-07-17 13:05:43

标签: javascript jquery

我正在做一些简单的JS / jQuery自动化,以便在Chrome中的Web应用程序上进行重复的工作。我有三个setTimeout函数,它们交错排列以不重叠。前两个可以正常工作,而第三个可以按应有的方式执行,但是当代码位于setTimeout函数内部时,代码不会单击文件上载按钮。

function fileUp(){
    console.log("trying to upload");
    var upload = $('form#my-dropzone.dropzone-button.dz-clickable');
    upload.click();
    console.log(upload);
}

var sku = setSKU();
searchSKU(sku);
var crd = setTimeout(function(){
    clickCard(sku,crd);
}, 3000);
var md = setTimeout(function(){
    mediaTab(md);
}, 5000);
var up = setTimeout(function(){
    fileUp();
}, 9000);

但是,当我在setTimeout之外调用fileUp()时,它运行良好。为什么会这样呢?

编辑1:

<form action="/imageupload/file" class="dropzone-button dz-clickable" id="my-dropzone">
        <div class="dz-text dz-message">
            <i class="icon-entypo-fix-picture extra-large-entypo-fix-icon box-title-icon"></i><p></p>
            Upload Media
        </div>
        <div id="dropzone-buttons">
            <a href="#" id="start-upload" class="link-button" style="display: none;">Start Upload</a>
            <a href="#" id="close-upload" class="link-button">Close</a><p></p>
            Drop files here or Click to Browse<p></p>
        </div>
        <input>
        <input>
        <input>
    </form>

日志:

[Violation] 'setTimeout' handler took 133ms
VM49737:23 clicked...
[Violation] 'setTimeout' handler took 135ms
entityView.js: Render Entity View
VM49737:31 trying to click
jquery-2.0.3.min.js:6 [Violation] 'load' handler took 890ms
VM49737:38 trying to upload
VM49737:41 init [form#my-dropzone.dropzone-button.dz-clickable, prevObject: init(1), context: document, selector: "form#my-dropzone.dropzone-button.dz-clickable"]

2 个答案:

答案 0 :(得分:0)

function fileUp(){
    console.log("trying to upload");
    var upload = $('form#my-dropzone.dropzone-button.dz-clickable');
    upload.click();
    console.log(upload);
}

$( document ).ready(function() {
    var sku = setSKU();
    searchSKU(sku);
    var crd = setTimeout(function(){clickCard(sku,crd)}, 3000);
    var md = setTimeout(function(){mediaTab(md)}, 5000);
    var up = setTimeout(function(){fileUp()}, 9000);
});

可能表格没有加载。用户.ready()函数应该可以正常工作

答案 1 :(得分:0)

我要做的是尝试修改“上载”的背景色,以确保正确选择了元素。

 $('form#my-dropzone.dropzone-button.dz-clickable').css('background-color', "green");

如果不执行任何操作,则表示选择器不返回任何内容。为了确切地告诉您这里出了什么问题,我们需要您要在此处选择的元素的html以及控制台日志。

我还要从第三个setTimeout中删除匿名函数,而直接将fileUp设置为回调函数:var up = setTimeout(fileUp, 9000);