In which case it is better to use the .append(), and which .appendTo()?

前端 未结 7 719
长情又很酷
长情又很酷 2021-01-12 04:48

There is no big difference between those functions except the syntax:

$(\'.target\').append(\'text\');
$(\'text\').appendTo(\'.target\');

A

7条回答
  •  广开言路
    2021-01-12 05:14

    I think there are two main points to consider:

    1. What do you already have references to? If you already have a jQuery object containing the elements you want to append then it makes sense to use .appendTo() rather than selecting the elements you want to append to and then using .append().

    2. Do you want/need to chain functions? One of the things that jQuery does well is allow you to chain functions together, because every function returns a jQuery object. Obviously if you want to call functions on the elements that you're appending, you'll want to use .appendTo() so that any functions you chain after that will apply to the elements being appended, not the elements being appended to.

提交回复
热议问题