javascript:如何正确循环此功能?

时间:2016-03-21 03:45:48

标签: javascript loops

我是js编码的新手,并尝试了许多不同的方法来循环这段代码,并且问我的朋友比我更熟练,而且他也不正确。我查了如何在js中使用循环,我似乎很难过,所以如果你还能给我一个关于js循环如何工作的基本解释,那就太棒了!

原始代码

function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1

}

setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow

}

partA(); // runs functions

原始代码本身工作正常,但它似乎永远不适用于我使用的任何循环。

最近一次循环尝试 - 注意:失败,显然

function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1

}

setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow

}

partA(); // runs functions

for (i = 0; i < 30; i++) {
text += “The number is ” + i + “<br>”;

}

提前谢谢! - 迈克尔

任何有关普遍改进代码的提示也会受到赞赏。

1 个答案:

答案 0 :(得分:0)

仍然无法确切地解决您的问题(看起来像:尝试在某些页面中自动执行某些重复性任务,而您无法控制其来源)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<title>JS Loop Example?</title>
<script>
function foo() {
    var div = $("#x")[0];
    div.innerHTML = "foo was clicked";
    for (i = 0; i < 5; i++) {
        div.innerHTML += "<br />!";
    }
    setTimeout(function(){ $('.barButton').click() }, 3000)
}
function bar() {
    var div = $("#x")[0];
    while (div.firstChild) {
        div.removeChild(div.firstChild);
    }
    var wibble = document.createTextNode('bar was clicked');
    div.appendChild(wibble);
    for (i = 0; i < 5; i++) {
        div.appendChild(document.createElement('br'));
        wibble = document.createTextNode('?');
        div.appendChild(wibble);
    }
    setTimeout(function(){ $('.fooButton').click() }, 3000)
}
</script>
</head>
<body onload='setTimeout(foo, 3000)'>
<script>
// Up until the close of the body, I can just write into the document.
document.write('<div id="x" class="stuffGoesHere">');
document.write('some random text<br />');
for (i = 0; i < 5; i++) {
    document.write('#<br />');
}
document.write('</div>');
document.write('<input type="button" class="fooButton" value="foo" onClick="foo()" />');
document.write('<input type="button" class="barButton" value="bar" onClick="bar()" />');
</script>
</body>
</html>