3

I am looping through images and create dynamic divs. But the images are not displayed, though console.log() shows that parameters of ready() function in the loop are valid. It shows myDiv1 and address of the first image in the array and myDiv2 and address of the second image. What's wrong with the code?

Here's my code:

<html>
<head>
<link rel="stylesheet" type="text/css" href="view_topic.css">
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<div id="outerdiv"></div>
<script>
$(document).ready(function() {
 $('#outerdiv').append(
 $('<div>').prop({
 id: 'myDiv1',
 //innerHTML: 'Hi there!',
 className: 'img-wrapper'
 })
 );
});
$(document).ready(function() {
 $('#outerdiv').append(
 $('<div>').prop({
 id: 'myDiv2',
 //innerHTML: 'Hi there!',
 className: 'img-wrapper'
 })
 );
});
$(this).css('height',"100px");
var get_a_image = ["http://iancaple.ru/upload/images/20200804_225812.jpg", "http://iancaple.ru/upload/images/8871677_tsumpy_laba_3.docx"];
var counter = 1;
var ready_cnt = 0;
for (var i = 0; i < 2; i++) {
 $(document).ready(function() {
 $('#myDiv' + ready_cnt + 1).append($('<img id="theImg2">').attr({
 'src': get_a_image[ready_cnt] , //'https://' + imgUrl ,
 'alt': 'test image ' + ready_cnt + 1
 })
 ).scrollTop(9999)
 console.log("get_a_image[" + ready_cnt + "]=" + get_a_image[ready_cnt]);
 console.log('#myDiv' + (ready_cnt + 1));
 ready_cnt++;
 });
}
</script>
 
</body>
<html>

StackByMe
6,57522 silver badges31 bronze badges
asked Nov 24, 2020 at 9:06
2
  • 1
    "Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute." (Source: jQuery Learning Center) - Why is this in a for loop? Commented Nov 24, 2020 at 9:11
  • What should I do? For loop is maybe a mistake. In my bigger code it is inserted as separate script in <?php while() { ?> Commented Nov 24, 2020 at 10:10

1 Answer 1

1

Use parentheses to get the increased value of ready_cnt. If not, it will be regarded to select an ID of myDiv01

$('#myDiv' + (ready_cnt + 1)).append(...)
answered Nov 24, 2020 at 9:10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.