简体   繁体   中英

Iterate through array and append each value into list

<ul>
<li></li>  
<li></li>   
<li></li>   
<li></li>   
<li></li>    
</ul>

var obj = { one:1, two:2, three:3, four:4, five:5 };

 var list = $("div");
    jQuery.each(obj, function(i, val) {
  list.html( val);
});

I am attempting to iterate through this array and append each value into the list items so that it appears as such:

<ul>
<li>1</li>  
<li>2</li>   
<li>3</li>   
<li>4</li>   
<li>5</li>   
</ul>

My problem is that the code only appeands the last item from the array: 5.

Not sure what I am doing wrong.

Use the value of the element to target the li it should be placed in:

$.each( obj, function( i, v ) {
  $("ul li").eq(v-1).html(v);
});

Demo: http://jsfiddle.net/3RAQC/

Results in the following:

<ul>
    <li>1</li>  
    <li>2</li>   
    <li>3</li>   
    <li>4</li>   
    <li>5</li>    
</ul>

Use list.append(val) not list.html(val)

.append() adds to the html content, while .html always replaces the whole html value with the parameter.

You neither have a <div> but an <ul> . You don't have an Array but an Object (which may be called associative array, ok). And you select one element, and (re)set its content in each iteration so that only the last value will appear. Better:

var ul = $('ul').empty();
$.each(obj, function(prop, val) {
    ul.append("<li>"+val+"</li>");
    // or better:
    $("<li>").text(val).appendTo(ul); // ?
});

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