简体   繁体   中英

Move a button created dynamically JavaScript

I am a very beginner! I've dynamically created a random number of buttons. After creation, I want them to automatically start moving. From some reason or another, my code creates the buttons , but doesn't make them move. Thanks a lot!

javascript.js

function myFunction() {
    for (i = 1; i<=Math.random() * 10; i++){
            var x = document.createElement("button");
            x.id = i;
            x.innerHTML = i;

            document.body.appendChild(x);
            moveMe(x.id);
            var v1 = Math.floor(Math.random() * 255);
            var v2 = Math.floor(Math.random() * 255);
            var v3 = Math.floor(Math.random() * 255);
            x.style.backgroundColor = "rgb(" + v1 + "," + v2 + "," + v3 + ")";

        }
}

function uMM(id){
    var x = document.getElementById(id);
    x.pozx = x.pozx + 1;
    x.pozy = x.pozy + 1;
    x.style.left = x.pozx + "px";
    x.style.top = x.pozy + "px";

}
function moveMe(id){
    var x = document.getElementById(id);
    x.pozx = 0;
    x.pozy = 0;
    setInterval( "uMM(" + id + ")", 1000);
}

home.php

<input type="text" id="demo">

Some points:

  • Loop conditions are evaluated at each iteration. Therefore, you were comparing each time against a new random number, so the probability of the number of buttons wasn't uniform.
  • You don't need IDs. Just pass a reference to the element as an argument or as the this value.
  • Don't use setTimeout nor setInterval with strings, because it's like evil eval ! Instead, use functions.

 (function myFunction() { for (var i=1, l=Math.random()*10; i<=l; ++i){ var x = document.createElement("button"); x.innerHTML = i; document.body.appendChild(x); moveMe(x); var rgb = Array.apply(null, Array(3)).map(function() { return Math.floor(Math.random() * 255); }).join(','); x.style.backgroundColor = "rgb(" + rgb + ")"; } })(); function uMM(){ var x = this; x.style.left = ++x.pozx + "px"; x.style.top = ++x.pozy + "px"; } function moveMe(x){ x.pozx = x.pozy = 0; setInterval(uMM.bind(x), 1e3); } 
 button { position: relative; } 

Your element-ID must begin with a letter ([A-Za-z]).

var x = document.createElement("button");
x.id = 'dyn-button-' + i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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