开发者

jQuery build table

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('<im开发者_开发知识库g 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 minimum iterations?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜