2015-10-06 134 views
-3

我得到5個按鈕,每次點擊都會觸發事件來實時生成新的不同按鈕。 問題是如何在2秒內模擬每個按鈕單擊事件。 像其他語言,使用javascript:模擬點擊每個按鈕

thread.sleep(2000); //將延遲2秒

在JavaScript中,這裏是一些方向Arguments.callee is deprecated - what should be used instead?

的setTimeout(函數(){... 的setTimeout(arguments.callee的, 100); },100); 另一個方向是jquery中的delay()函數

但是它可以觸發生成按鈕事件嗎?

$(document).ready(function() { 
 
    timer(); 
 
}); 
 

 
function timer() { 
 
    setTimeout(function() { 
 

 
    setTimeout(arguments.callee, 2000); 
 
    }, 2000); 
 

 
}; 
 

 
function addBtn(btn) { 
 
    $("#p2").text(btn.value) // btn.value; 
 
    var count = Math.round((Math.random() * 2 * 1000)/1000, 0) + 1; 
 
    console.log(count); 
 
    $(".addbtn").remove(); 
 
    for (i = 0; i < count; i++) { 
 
    $("#d2").append("<input class='addbtn' type='button' style='width:100px;color:green' value='subBtn" + btn.value + "_" + (i + 1) + "'/>") 
 
    } 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="d1"> 
 
    <input id="btn1" type="button" onclick="addBtn(this)" style="width:100px;color:green" value="1" /> 
 
    <input id="btn2" type="button" onclick="addBtn(this)" style="width:100px;color:green" value="2" /> 
 
    <input id="btn3" type="button" onclick="addBtn(this)" style="width:100px;color:green" value="3" /> 
 
</div> 
 
<div id="d2"> 
 

 
</div>

回答

0

如果你有五個按鈕,並希望點擊它們各自爲了,點擊一個每兩秒鐘,你會使用$()找一找,那麼,你會使用setTimeout安排點擊。

您沒有示出的任何標記或代碼,但是,例如,該點擊每五個按鈕的點擊次數之間的兩秒延遲(沒有初始延遲):

// Look up the buttons 
 
var btns = $("input[type=button]"); 
 

 
// Something so we can see them get clicked 
 
btns.on("click", function() { 
 
    $("<p>").text("Button " + this.value + " clicked").appendTo(document.body); 
 
}); 
 

 
// Loop through them, scheduling a click on each one after 2000ms 
 
// (two seconds). Note how we're multiplying 2000 by the index 
 
// of the button -- the first button is index 0, so that's 0ms 
 
// (almost immediate), the second is index 1 = 2000ms from now, 
 
// the third is index 2 = 4000ms from now... 
 
btns.each(function(index) { 
 
    var $btn = $(this); 
 
    setTimeout(function() { 
 
    $btn.click(); 
 
    }, 2000 * index); 
 
});
<input type="button" value="One"> 
 
<input type="button" value="Two"> 
 
<input type="button" value="Three"> 
 
<input type="button" value="Four"> 
 
<input type="button" value="Five"> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

這只是幾種不同方式之一。

+0

謝謝,你能幫助更新問題嗎? – MaxJ