Click function clears all HTML elements
P粉574695215
P粉574695215 2023-09-10 23:27:38
0
1
650

<!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>

I don't know why all the elements disappear, even when clicking any of the buttons, for those wondering, I'm trying to make a collectible car card game website.

P粉574695215
P粉574695215

reply all(1)
P粉348088995

open() is already the name of a function that opens a new page, so when the button is clicked, the open() function will be called and opened A blank page. Just change your function name:

<!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>

Also, consider changing your code to use event listeners and variables. Here's a better practice:

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template