Générer une ID unique en Javascript
Dans ce tutoriel nous allons découvrir comment générer une ID unique. Javascript ne possède pas de méthode intégrée pour générer des identifiants uniques, mais on peut utiliser une méthode appelée Math.random() qui génère une chaîne alphanumérique unique à chaque appel.
Exemple:
<!DOCTYPE html>
<html>
<body>
<p>Cliquez sur le bouton pour générer une ID unique.</p>
<button onclick="generate()">Cliquez ici</button>
<p id="uniqueID"></p>
<script>
function generate() {
let id = () => {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
document.getElementById("uniqueID").innerHTML = id();
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>Cliquez sur le bouton pour générer une ID unique.</p>
<button onclick="generate()">Cliquez ici</button>
<p id="uniqueID"></p>
<script>
function generate() {
let id = () => {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
document.getElementById("uniqueID").innerHTML = id();
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <p>Cliquez sur le bouton pour générer une ID unique.</p> <button onclick="generate()">Cliquez ici</button> <p id="uniqueID"></p> <script> function generate() { let id = () => { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } document.getElementById("uniqueID").innerHTML = id(); } </script> </body> </html>
Résultat |
---|
Cliquez sur le bouton pour générer une ID unique. |