I have this function, and I'm trying to display photos using loop.
in name1 I have the file location of the photos, every loop I change photo so the location is obviously changed.
in console.log
I do see the file, for example "cardImages/7_of_diamonds.png ".
now the problem that I have is that I don't really understand how to display the photos and keep them there, so I have 2 ways that I found but they don't actually work. and the end result should looks like the photo I added to the post. the first loop for the ph1 id. and the second loop for the ph2 id. what I'm missing here? example
//$("#ph1").append("<img src='name1'>");
//result.innerHTML = "<img src=''${name2}'' alt='ph2' />";
function DisplayUsingLoop(pla1, numb1) {
var name1;
for (i = 0; i < numb1; i ) {
name1 = pla1[i].img
console.log(name1)
result.innerHTML = "<img src=''${name2}'' alt='ph2' />";
}
for (i = 0; i < numb2; i ) {
name1 = pla2[i].img
console.log(name1)
$("#ph1").append("<img src='name1'>");
}
<body>
<input type="button" value="Start" onclick="start()" />
<div id="container">
<div id="ph1">
Player 1:
</div>
<div id="ph2">
Player 2:
</div>
</div>
CodePudding user response:
To display photos using a loop, use the for loop. First of all, you need to put your js inside of tags, like this:
<script>
//this is js
</script>
Player1:
//this is js
let div = document.getElementById(`ph1`)
for (let i = 0; i < 5; i ) {
div.innerHTML = `<img src=`your_image_file_name`></img>`
}
if you want different images each time, then manually do it without a loop:
//this is js
let div = document.getElementById(`ph1`)
div.innerHTML = `<img src=`img1.png`></img>`
div.innerHTML = `<img src=`img2.png`></img>`
Also, try to learn js and html using w3schools before you start coding this stuff.
Also, you are using jQuery, which you need to import using html before you start your js.
Also, try using strict html formatting and put js at the end of your body.
CodePudding user response:
Try this
your start function should contain your players' card arrays.
function start(){
var cards1 = ["cardImages/A_of_diamonds.png", "cardImages/2_of_diamonds.png", "cardImages/3_of_diamonds.png", "cardImages/4_of_diamonds.png"];
var cards2 = ["cardImages/10_of_diamonds.png", "cardImages/J_of_diamonds.png", "cardImages/Q_of_diamonds.png", "cardImages/K_of_diamonds.png"];
DisplayUsingLoop(cards1, 4, "ph1");
DisplayUsingLoop(cards2, 4, "ph2");
}
To the DisplayUsingLoop function I added the idPlayer
function DisplayUsingLoop(pla1, numb1, idPlayer)
CodePudding user response:
Maybe use a class in your divs like 'ph' and then use something like this:
let x=document.getElementsByClassName('ph');
Array.from(x).forEach((el)=> {
el.innerHTML = `<img src=`image_src_name`></img>`
};