问题:
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>