const btn = document.getElementById('btn'); btn.addEventListener('click', () => { document.body.style.backgroundColor = changeC() }); var x = Math.floor(Math.random() *256); y = Math.floor(Math.random() * 256); z = Math.floor(Math.random() * 256); function changeC() { return "rgb(" + x + "," + y + "," + z + ")"; }; First click changes the background color. Consecutive clicks don't. How to modify code so that consecutive clicks will also change the background color randomly?
5 Réponses :
Exécuter ce code
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <button id="btn">change color</button> <script> const btn = document.getElementById('btn'); btn.addEventListener('click', () => { document.body.style.backgroundColor = changeC() }); function changeC() { var x = Math.floor(Math.random() * 256); y = Math.floor(Math.random() * 256); z = Math.floor(Math.random() * 256); return "rgb(" + x + "," + y + "," + z + ")"; }; </script> </body> </html>
Votre x code>
y code> et
z code> n'a été attribué qu'une seule fois, car le programme a démarré, car ils étaient à la portée de haut niveau . Pour les réaffecter à chaque fois, déplacez-les dans la fonction comme indiqué.
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
document.body.style.backgroundColor = changeC()
});
function changeC() {
var x = Math.floor(Math.random() *256),
y = Math.floor(Math.random() * 256),
z = Math.floor(Math.random() * 256);
return "rgb(" + x + "," + y + "," + z + ")";
};
@iamoren a souligné, votre y code> et
z code> ne faisiez pas partie de la déclaration
var code>. J'ai corrigé cela dans ma réponse en utilisant
, code> au lieu de
; code>. Auparavant, cela aurait fonctionné, mais
y code> et
z code> aurait été des variables globales au lieu de la fonction locale à la fonction
ChangeC code>.
Mettez à jour votre fonction identique à suivre:
function changeC() { x = Math.floor(Math.random() *256); y = Math.floor(Math.random() * 256); z = Math.floor(Math.random() * 256); return "rgb(" + x + "," + y + "," + z + ")"; };
<h1>This works</h1> <button id="btn"> PRESS ME </button>
Essayez ceci:
p>
<button id="btn"> Click me </button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
mettre la fonction x y z
Notez que
y code> et
z code> ne faisant pas partie de
var code> car
var code> terminé par un point-virgule (
< / code>). Ajouter
var code> avant
y code> et
z code> ou, remplacez le point-virgule après
x code> et
y Code> à une virgule (
, code>).