For loop syntax in Javascript
Ad
I am trying to create a loop to show 5 images using Javascript. I am having some trouble understanding the syntax.
This is what I have so far.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Challenge: Daisy chain</title>
</head>
<body>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script>
var image = $("<img>")
.attr('src', 'https://upload.wikimedia.org/wikipedia/commons/2/29/English_Daisy_(Bellis_Perennis).jpg')
.attr('width', '10')
.attr('alt', 'new name')
.appendTo('body');
for(i = 0, i < 5, i++) {
$(image).appendTo('body');
}
</script>
</body>
</html>
Ad
Answer
Ad
You have to actually create the images inside the loop to get five images, otherwise you only get one image, that you append five times, but it's still just one single image
for(i = 0; i < 5; i++){
$("<img />", {
src : 'https://upload.wikimedia.org/wikipedia/commons/2/29/English_Daisy_(Bellis_Perennis).jpg',
width : 10,
alt : 'new name'
}).appendTo('body');
}
Also note that jQuery can take the attributes/properties directly when constructing elements
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad