简体   繁体   中英

how to return an array value to dynamically created elements with vanilla javascript

I have an array of values and when I click on a dynamically created div, one of the values is randomly assigned to it. I'd like to display the value of the array item on the page when I click on the dynamically created div, but I can't figure out how to do it. I get the values returned when I use console.log or alert, but for the life of me can't figure out how to get the values to display on the actual page. I am pretty new to javascript and would appreciate any help on this - here's what I have so far:

<div id="gameboard"></div>

the 16 dynamically created divs are created under the #gameboard div and have the class .cards, I've styled them with css.

#gameboard {
display: flex;
width: 800px;
height: 575px;
min-height: 575px;
margin-right: auto;
margin-left: auto;
padding-top: 1rem;
padding-bottom: 1rem;
flex-wrap: wrap;
justify-content: center;
align-items: center;
background-color: #dadfe8;
}
.cards {
width: 150px;
height: 100px;
margin-right: 5px;
margin-left: 5px;
padding-top: 2rem;
border: 2px solid black;
border-radius: 5px;
background-color: #3065ba;
font-size: 4rem;
text-align: center;
cursor: pointer;
}

here is the javascript:

var tileImages = ['A','B','C','D','E','F','G','H'];
var gameboard = document.getElementById('gameboard');
var solutionArray = tileImages.concat(tileImages); 

shuffleArray(solutionArray);
console.log(solutionArray);  to
function shuffleArray(d) {
 for (var c = d.length - 1; c > 0; c--) {
  var b = Math.floor(Math.random() * (c + 1));
  var a = d[c];
  d[c] = d[b];
  d[b] = a;
 }
return d
};

startGame();

function startGame() {
 var clearedBoard = gameboard.innerHTML = "";
 for (var i=0; i<= ((solutionArray.length)-1); i++) {
  var cards = gameboard.innerHTML += '<div class="cards"></div>';
 }
};
var randomValue = gameboard.onclick = function() {
console.log(tileImages[Math.floor(Math.random() * tileImages.length)]);
};

You are on the right track!

Just move the display logic from the gameboard to the cards themselves.

To do that, use the Document api to create the cards instead of defining them as strings. Then it is easy to attach an onclick callback that handles it's display logic.

function startGame() {
for (var i = 0; i <= ((solutionArray.length) - 1); i++) {
    var card = document.createElement("div");
    card.classList.add('cards');
    card.onclick = function() {
        this.innerHTML = tileImages[Math.floor(Math.random() * tileImages.length)];
    }
    gameboard.appendChild(card);
}

}

It's also probably a good idea to remove the rogue 'to' in line 6.

EDIT: Removed the arguments from startGame function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM