Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

Separating code for QRcode image generator Javascript/HTML

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

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

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...