简体   繁体   English

单击按钮即可无限调用 javascript 函数?

[英]Calling a javascript function infinitly on click of a button?

Okay so this is a bit of a weird request.好吧,这是一个有点奇怪的请求。 So I've programmed tiles that generate using JavaScript (with the help of people here on stack overflow) now I would like to make it so that on the click of a button my changecolors function is called a set number of times so that the colors of the tiles randomly change before your eyes.所以我已经编写了使用 JavaScript 生成的图块(在堆栈溢出的人的帮助下)现在我想这样做,以便在单击按钮时我的 changecolors 函数被调用一定次数,以便颜色的瓷砖在您眼前随机变化。 I've got a button that every time you click it the colors change, but how can I make it so on that click they continuously change?我有一个按钮,每次点击它时颜色都会改变,但是我怎样才能让它在点击时不断变化呢? I've tried using the JavaScript function set Interval(function, time) and couldn't seem to get it to work.我已经尝试使用 JavaScript 函数 set Interval(function, time) 并且似乎无法让它工作。 Just in case, I will also inform you that I am putting a button in that will also stop the random color changes.. Here's the code.以防万一,我还会通知您,我正在放置一个按钮,该按钮也将停止随机颜色更改。这是代码。 Any help would be great!!任何帮助都会很棒!!

<!doctype html>
<html>
<style>
.cell {
  width: 100px;
  height: 100px;
  display: inline-block;
  margin: 1px;
  padding:4px;
}
button{
float:left;
padding:4px;
}
</style>


<title></title>
<head><script type="text/javascript">
function generateGrid(){
  for (i = 0; i < 5; i++) {
    for (b = 0; b < 5; b++) { 
      div = document.createElement("div");
      div.id = "box" + i +""+ b;
      div.className = "cell";
      document.body.appendChild(div);
    }
    document.body.appendChild(document.createElement("br"));
  }
}
function changeColors(){
for(i =0;i < 5; i++){
    for (b=0;b<5;b++){
        var holder=document.createElement("div");
        holder=document.getElementById("box" + i +""+ b);
        holder.style.backgroundColor = getRandomColor();

    }
}

}
function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
</script>
</head>


<body>
<script>

generateGrid();

changeColors();


</script>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="window.setInterval(changeColors(),2000);">Click me to start cycle</button>
</body>





</html>

Your setTimeoutFunction was not sintatically correct您的 setTimeoutFunction 不正确

 var stop = false; function generateGrid(){ for (i = 0; i < 5; i++) { for (b = 0; b < 5; b++) { div = document.createElement("div"); div.id = "box" + i +""+ b; div.className = "cell"; document.body.appendChild(div); } document.body.appendChild(document.createElement("br")); } } function changeColors(){ for(i =0;i < 5; i++){ for (b=0;b<5;b++){ var holder=document.createElement("div"); holder=document.getElementById("box" + i +""+ b); holder.style.backgroundColor = getRandomColor(); } } } function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } document.addEventListener("DOMContentLoaded", function(event) { generateGrid(); changeColors(); });
 .cell { width: 100px; height: 100px; display: inline-block; margin: 1px; padding:4px; } button{ float:left; padding:4px; }
 <!doctype html> <html> <title></title> <body> <button onclick="changeColors();">Click me to change colors</button> <button onclick="window.setInterval(function(){changeColors();},2000);">Click me to start cycle</button> </body> </html>

Edited to work without jQuery编辑后可以在没有 jQuery 的情况下工作

Your changeColors() should have been changeColors for window.setInterval .changeColors()应该已经changeColorswindow.setInterval

I cleaned up your code and added the stop/start buttons.我清理了您的代码并添加了停止/开始按钮。 By creating an array of elements, it saves the changeColors function having to locate each element every iteration.通过创建一个元素数组,它节省了每次迭代都必须定位每个元素的 changeColors 函数。 Lastly I changed your generateGrid function to accept a width and height.最后,我更改了 generateGrid 函数以接受宽度和高度。 A bit overkill but I got carried away :)有点矫枉过正,但我​​被带走了:)

HTML HTML

<button onclick="changeColors();">Click me to change colors</button>
<button onclick="startCycle();">Start cycle</button>
<button onclick="stopCycle();">Stop cycle</button>
<br>
<br>

JavaScript JavaScript

var elements = [];
function generateGrid(width, height) {
    for (var y = 0; y < height; y++) {
        for (var x = 0; x < width; x++) {
            var div = document.createElement("div");
            div.id = "box" + y + "" + x;
            div.className = "cell";
            document.body.appendChild(div);
            elements.push(div);
        }
        document.body.appendChild(document.createElement("br"));
    }
}

function changeColors() {
    for (e in elements) {
        elements[e].style.backgroundColor = getRandomColor();
    }
}

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

var interval = null;
function startCycle() {
    if (interval) return;
    interval = window.setInterval(changeColors, 500);
}

function stopCycle() {
    clearInterval(interval);
    interval = null;
}

generateGrid(3, 5);
changeColors();

Demo演示

Simple Just added one function on Click of button try this:简单 刚刚在点击按钮上添加了一个功能试试这个:

 <style> .cell { width: 100px; height: 100px; display: inline-block; margin: 1px; padding:4px; } button{ float:left; padding:4px; } </style> <title></title> <head><script type="text/javascript"> function generateGrid(){ for (i = 0; i < 5; i++) { for (b = 0; b < 5; b++) { div = document.createElement("div"); div.id = "box" + i +""+ b; div.className = "cell"; document.body.appendChild(div); } document.body.appendChild(document.createElement("br")); } } function changeColors(){ for(i =0;i < 5; i++){ for (b=0;b<5;b++){ // var holder=document.createElement("div"); var holder=document.getElementById("box" + i +""+ b); holder.style.backgroundColor = getRandomColor(); } } } function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } </script> </head> <body> <script> generateGrid(); changeColors(); function animate1() { setInterval(function(){ changeColors(); },5000); } </script> <button onclick="changeColors();">Click me to change colors</button> <button onclick="animate1();">Click me to start cycle</button> </body>

Note: setTimeout function gets called only once after your set duration where setTimeout gets called indefinite unless you use clearInterval() to Stop it.注意: setTimeout 函数仅在您设置的持续时间之后调用一次,除非您使用 clearInterval() 停止它,否则 setTimeout 被无限期调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM