views:

60

answers:

2

menuOrder is an empty div

$("#menuOrder").append('<table>');
                $(menus).each(function(i, menu) {

                    $("#menuOrder").append('<tr><td>');
                    $("#menuOrder").append(menu.text);
                    $("#menuOrder").append('</td><td>');

                    if (i > 0) {
                        $("#menuOrder").append('<img src="/images/_images/up.png" />');
                    }
                    else {
                        $("#menuOrder").append('<img src="/images/_images/blank.png" />');
                    }

                    if (i < menus.length - 1) {
                        $("#menuOrder").append('<img src="/images/_images/down.png" />');
                    }

                    $("#menuOrder").append('</td>');
                    $("#menuOrder").append('</tr>');

                });

                $("#menuOrder").append('</table>');

this code not work properly, how can i change it with mininun iterations?

+2  A: 

Try doing something like this:

var rows = [];
$(menus).each(function(i, menu) {
 var row = '<tr><td>'.menu.text.'</td><td>';

    if (i > 0) {
        row +='<img src="/images/_images/up.png" />';
    }
    else {
        row +='<img src="/images/_images/blank.png" />';
    }

    if (i < menus.length - 1) {
       row +='<img src="/images/_images/down.png" />';
    }

    row += '</td></tr>';
    rows.push(row);
});
$('<table></table>').append(rows.join('')).appendTo('#menuOrder');

This fills the rows array with a string that contains the HTML for each row. When its done creating all the rows then it creates a jQuery Object of a table element and appends all the rows to it. It then appends the table to #menuOrder.

PetersenDidIt
I'd also mention that it is better to add all rows at once, storing html for them in a single string. some browsers has issues while manipulating parts of table's inner html
vittore
A: 

Note that with append() you can't do this:

$("#menuOrder").append('</table>');

Instead of glueing together pieces of HTML strings, you must think in terms of complete DOM nodes. Examples of valid arguments for append():

.append($('.something'))
.append(document.createElement('div'))
.append('<div />') // automatically creates empty div element
.append('<tr><td></td></tr>') // automatically creates tr with td inside
jholster