开发者

Jquery append() method and chaining order debug

I am attempting to insert a new row into a table with Jquery. Can someone comment between the two techniques:

  1. This works correctly:

    $('<tr>').append(row).appendTo(table);
    
  2. This does not work, but it is not clear why?

    开发者_开发知识库$(row).appendTo($('<tr>')).appendTo(table);
    


$(row).appendTo($('<tr>').appendTo(table)); 

Try that. It looks like you just placed your parentheses in the wrong order.


$(row).appendTo($('<tr>'))

This adds row to a newly created <tr>. This returns a jQuery reference to row - NOT to the newly created <tr>

                          .appendTo(table);

Adds row to table, thus removing it from the newly created <tr>.

Try this instead. It gets the references straight.

$('<tr>').append(row).appendTo(table);


Your scope is off. appendTo will not change the scope of the chain. You're appending row a dynamic tr, then immediately appending it to the table.


Snowblind's solution will work, this will work: $(table).append($(row).wrap('<tr></tr>'));

There are probably a bunch of other derivations. Just make sure you take a bit of chain understanding from this. : )


In your second example...

$(row).appendTo($('<tr>')).appendTo(table);

The set when you call appendTo() the second time is not what you think it is. It will be row.

This jsFiddle should make it clearer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜