I made a function that shows card images after I click a button. the problem is that it doesn't work on chrome. the chrome editor presents an extra '/' to the end of the path.
function renderDeck(deck,ph)
{
var htmlStr = document.getElementById(ph).innerHTML;
for (var i = 0; i < deck.length; i ) {
htmlStr = '<div>';
htmlStr = '<img src=' deck[i].path '/>';
htmlStr = '</div>';
}
document.getElementById(ph).innerHTML = htmlStr;
}
An example of what I push inside the deck
deck.push({ name: 'red_joker', path: 'cardImages/red_joker.png', val: 15 });
what can be the problem?
CodePudding user response:
let src = 'https://asia.olympus-imaging.com/content/000107507.jpg';
function renderDeck() {
var htmlStr = document.getElementById('test').innerHTML;
htmlStr = '<div>';
htmlStr = '<img src=' src ' />';
htmlStr = '</div>';
document.getElementById('test').innerHTML = htmlStr;
}
renderDeck();
<div id="test"></div>
You have to add a space before the closing tag. In the line htmlStr = '<img src=' deck[i].path ' />';
function renderDeck(deck,ph)
{
var htmlStr = document.getElementById(ph).innerHTML;
for (var i = 0; i < deck.length; i ) {
htmlStr = '<div>';
htmlStr = '<img src=' deck[i].path ' />';
htmlStr = '</div>';
}
document.getElementById(ph).innerHTML = htmlStr;
}
CodePudding user response:
Off Topic: Avoid innerHTML = ...
because
- it has to serialize and then parse all existing dom nodes
- it replaces all existing nodes with copies/new ones, so things like event handler, references you've kept, all will be gone. Everything that is not expressed in the markup itself.
function renderDeck(deck, ph) {
// create the markup for the new items
const htmlStr = deck.map(item => `<div><img src="${item.path}"></div>`).join("\n");
// parse the `htmlStr` into a DOM Node that you can add to other DOM Nodes.
const fragment = document.createRange().createContextualFragment(htmlStr);
// append the DocumentFragment to the existing element.
document.getElementById(ph).append(fragment);
}
And a link for those that don't know yet what a DocumentFragment is.