gpt4 book ai didi

javascript - 普通 JS : How do I return dynamic html so I can reuse it in element. insideHTML?

转载 作者:行者123 更新时间:2023-12-03 01:08:26 25 4
gpt4 key购买 nike

我正在构建的内容:大家好,我正在尝试构建一个内存游戏,为了做到这一点,我必须洗牌并将卡片重新插入 HTML 中。

问题:我在将洗牌组的 HTML 重新插入 DOM 时遇到问题,因为它似乎返回值“null”。

我尝试解决这个问题

我创建了函数createHTML,它的目的是编译由generateCardHTML生成的所有html,并返回html。然而,“return Deck”似乎没有做任何事情,尽管 console.log(deck) 返回的 html 完全符合我的预期。

cards = ['card1', 'card1',
'card2','card2',
'card3','card3',
];


function initGame() {
const shuffledCards = shuffle(cards);

// generates each li
function generateCardHTML(card) {
return `<li class="card"><i class="${card}"></i></li>`
};

// PROBLEM BEGINS HERE

function createHTML(){
let deck = "";
shuffledCards.forEach(function(card) {
const genHTML = generateCardHTML(card);
deck += genHTML;
})
return deck;
};
createHTML();
};

initGame();

const gameDeck = document.querySelector('.card');

gameDeck.innerHTML = initGame();


// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;

while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
}

我发现最接近我的问题的是 this但它似乎没有解决同一问题。要么是我太缺乏经验,无法理解它。

最佳答案

因为 initGame() 没有返回值,所以在这种情况下您必须返回一个值,即 createHTML() 的返回值。

像这样

cards = ['card1', 'card1',
'card2', 'card2',
'card3', 'card3',
];


function initGame() {
const shuffledCards = shuffle(cards);

// generates each li
function generateCardHTML(card) {
return `<li class="card"><i class="${card}"></i> ${card}</li>`
};

function createHTML() {
let deck = "";
shuffledCards.forEach(function(card) {
const genHTML = generateCardHTML(card);
deck += genHTML;
})

return deck;
};

// NEED TO RETURN SOMETHING
return createHTML();
};

// THERE IS NO NEED FOR THIS
// initGame();

const gameDeck = document.querySelector('.card');

gameDeck.innerHTML = initGame();


// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;

while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
}
<ul class='card'></ul>

我还将 card 值作为文本添加到 li 中,以便您可以看到它,尝试运行代码,您将获得正确的输出

关于javascript - 普通 JS : How do I return dynamic html so I can reuse it in element. insideHTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52287660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com