Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I tested the code only on HTML it worked just fine, but when I separate it doesn't show -surprise - here's my code:

<!DOCTYPE html>
<html>
<body>
<img id='qrcode' src=''>
<button onclick="newQR()">Gerar QRcode</button>
<script>
  function newQR() {
    var x = Math.floor((Math.random() * 99) + 1);
    document.getElementById('qrcode').src = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x
  }
  newQR()
</script>
</body>
</html>

EDIT: I want to separate them, for example, having the function newQR inside script.js and the rest inside index.html, like this:

 script.js
    function newQR() {
    var x = (Math.random() * 99999999999999999);
    document.getElementById('qrcode').src ="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x
    return 
  }

index.html

 <!DOCTYPE html>
 <html>
 <body>
 <button onclick="newQR()">Gerar QRcode</button>
   <img = 'qrcode' />
    <script type="js/javascript" src="script.js"></script>
  </body>
 </html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
274 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your problem could simply be that you've forgotten the id attribute within this line of your HTML <img = 'qrcode' />

Try changing that to this: <img id='qrcode' src=''>

However, if after trying... the problem at hand still persists then I'd recommend you to try the examples below.

Change your HTML markup to this:

<body>
  <img id='qrcode' src=''>
  <button id="Btn">Gerar QRcode</button>
  <script type="text/javascript" src="script.js"></script>
</body>

Within your javascript file simply implement this:

document.getElementById("Btn").addEventListener("click", function(){
    var x = (Math.random() * 99999999999999999);
    document.getElementById('qrcode').src ="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x;
});

or this version of javascript if you prefer:

document.getElementById("Btn").addEventListener("click", newQR);

function newQR() {
   var x = (Math.random() * 99999999999999999);
   document.getElementById('qrcode').src ="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...