trying to make randomised stats (of a RPG character) render in web browser (JavaScript)

问题: Total JavaScript noob here. I am coding a character creation system in JavaScript. My problem is that I cannot get my randomised stats render in browser. I can get them ren...

问题:

Total JavaScript noob here. I am coding a character creation system in JavaScript. My problem is that I cannot get my randomised stats render in browser. I can get them render in console though. I have my .HTML file linked with my .JS file. I tried to find a answer to this but could not find it. Thank you.

const stats = ['Vitality','Strength', 'Agility', 'Dexterity', 'Wisdom', 'Charisma', ]

stats.forEach(function (item, index) {
    
    console.log(item, Math.floor(Math.random() * 10) + 1)
    
})
 

回答1:

I'm hoping this is the solution you're looking for.

Click the button "Run code snippet" to see it in action.

<html>
  <head>
  <title>Random Stats</title>
  </head>
  <body>
    <h1>Stats</h1>
    <div id="stats"></div>
     
    <!-- NOTICE THIS AT THE BOTTOM OF THE BODY TAG -->
    <!-- This is so it can load the page and find the dom element -->
    <script type="text/javascript">
    // 1. Create Your List
    const stats = ['Vitality','Strength', 'Agility', 'Dexterity', 'Wisdom', 'Charisma'];

    // 2. Choose the dom element you want to add to
    const statsElement = document.querySelector('#stats');

    // 3. Append stats for each to dom element
    stats.forEach(function (item, index) {
      // Notice the += to add to what already exists
      statsElement.innerHTML += item + ":" + (Math.floor(Math.random() * 10) + 1) + "<br />";
    });
    </script>
  </body>
</html>


回答2:

Use "Run code snippet" to see how it looks like

const stats = ['Vitality','Strength', 'Agility', ];
const statsValues = {};
// Generate object what contains your values { 'Vitality': 4, 'Strength': 5 etc}
for (let i = 0; i < stats.length; i += 1) {
  const nameStat = stats[i];
  statsValues[nameStat] = Math.floor(Math.random() * 10) + 1;
}

// apply them to HTML
for (let i = 0; i < stats.length; i += 1) {
  const nameStat = stats[i];
  document.querySelector(`#${nameStat}`).innerHTML = `${nameStat}: ${statsValues[nameStat]}`;
}
// You can do it in one for, or in forEach if you like
<html>
  <head>
  <title>Random Stats</title>
  </head>
  <body>
    <h1>Stats</h1>
    <div id="Vitality"></div>
    <div id="Strength"></div>
    <div id="Agility"></div>
  </body>
</html>

  • 发表于 2020-06-27 19:16
  • 阅读 ( 127 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除