<!DOCTYPE html> <html> <head> </head> <button id="someid" onclick="open()">打开一包卡牌</button> <button id="somid" onclick="view()">查看车库</button> <body> <p id="demo"></p> </body> <script> function open(){ itms = ['2014 Nissan 350z', '2019 VW golf GTI ', '1995 Mazda 323 Protoge', '1990 BMW 8-series', '1990 ford mustang svt cobra', '1990 mazda rx7', '1990 nissan skyline gt-r']; itm = itms[Math.floor(Math.random()*itms.length)]; console.log(itm) } function view(){ document.getElementById("demo").innerHTML = ""+itm+"" } </script> </html>
我不知道為什麼所有的元素都消失了,甚至在點擊任何一個按鈕時都會消失,對於那些想知道的人,我正在嘗試製作一個汽車收藏卡牌遊戲網站。
P粉3480889952023-09-11 00:57:23
open()
已經是一個開啟新頁面的函數的名稱,所以當按鈕被點擊時,會呼叫open()
函數並打開一個空白頁面。只需更改您的函數名稱:
<!DOCTYPE html> <html> <head> </head> <button id="someid" onclick="openpack()">打开一个卡包</button> <button id="somid" onclick="view()">查看车库</button> <body> <p id="demo"></p> </body> <script> function openpack(){ itms = ['2014 Nissan 350z', '2019 VW golf GTI ', '1995 Mazda 323 Protoge', '1990 BMW 8-series', '1990 ford mustang svt cobra', '1990 mazda rx7', '1990 nissan skyline gt-r']; itm = itms[Math.floor(Math.random()*itms.length)]; console.log(itm) } function view(){ document.getElementById("demo").innerHTML = ""+itm+"" } </script> </html>
另外,請考慮將您的程式碼變更為使用事件監聽器和變數。這是更好的實踐方法:
const itms = ['2014 Nissan 350z', '2019 VW golf GTI ', '1995 Mazda 323 Protoge', '1990 BMW 8-series', '1990 ford mustang svt cobra', '1990 mazda rx7', '1990 nissan skyline gt-r']; let itm; document.getElementById('open').addEventListener('click', () => { itm = itms[Math.floor(Math.random()*itms.length)]; console.log(itm) }); document.getElementById('view').addEventListener('click', () => { document.getElementById("demo").innerHTML = ""+itm+"" });
<!DOCTYPE html> <html> <head> </head> <body> <button id="open">打开一个卡包</button> <button id="view">查看车库</button> <p id="demo"></p> </body> </html>