简体   繁体   中英

add <li></li> inside <ul> dynamically which contains <img> tag inside <li>

After ul tag i want to call function in javascript to add list item dynamically and inside i want to place image tag as shown below.

<li> <img src="images/testpic" height="200px" width="200px" /> </li> 

i have used .append() method in jquery but doesn't work

<script type="text/javascript">
                '$('ul').append("<li><img src='thumbs/image"+i+".jpg' width='175' height='175' /></li>");
                '$('ul').append("<li><img src='thumbs/image"+i+".jpg' width='175' height='175' /></li>");
                '$('ul').append("<li><img src='thumbs/image"+i+".jpg' width='175' height='175' /></li>");

From a for loop

for ( var i = 0; i < 10; i++ ) {
    $("<li>",{ html:'<img src="http://placekitten.com/100/100?image='+i+'" />' })
        .appendTo("#images");   
}​

From an Array of Images

If all you're wanting to do is add list items with images inside:

// You have a mention of i in your example, so I assume you are
// cycling over some sort of list - so I'll do the same
​var images = [ 'http://placekitten.com/50/50', 
               'http://placekitten.com/50/50?image=2' ];

// You had some malformed markup in your code, the following keeps it simple
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​$.each( images, function( i, v ) {
    $("<li>", { html: '<img src="' + v + '" />' }).appendTo("#images");        
});​

Fiddle: http://jsfiddle.net/YwH7Z/

Assuming your image number starts at 0 ...

$('ul').each(function(i) {
    $(this).append("<li><img src='thumbs/image"+i+".jpg' style='width:175px; height:175px; '/></li>");
});

Example

Assuming it starts at 1 ..

$('ul').each(function(i) {
    $(this).append("<li><img src='thumbs/image"+(i+1)+".jpg' style='width:175px; height:175px; '/></li>");
});

Example

$('ul').each(function() {
   $(this).append("<li><img src='thumbs/image"+i+".jpg' width='175' height='175'/></li>");
});

can fix error by the steps below:

  1. You sure that using $('ul') can find the ul tag element? If not, please put your code in $(function(){/**put your append code**/}) , and make sure <body> contains <ul> element.
  2. You sure that appended html is formatted? Put " li><img src='thumbs/image"+i+".jpg' width='175' height='175' /></li>> " into <ul> , then see the li is shown on the browser?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM