<!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>
我不知道为什么所有的元素都消失了,甚至在点击任何一个按钮时都会消失,对于那些想知道的人,我正在尝试制作一个汽车收藏卡牌游戏网站。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
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+"" });