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

前端 未结 7 713
长情又很酷
长情又很酷 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:17

    In context

    • Personally I use the two functions depending on what set of instructions my function is doing or where they are used (the context), the way you read the code may change the way you prefer to write the code and it may feel better either way subjectively to your own.

    Either way, it's fairly literal and i find myself writing each automatically without thinking.

    In each context, if the subject is the area you are manipulating,


    $(target).append(content)
    //within a function based around manipulating a specific area
    

    seems to make more sense whereas if the subject of the function is new content then

    $(content).appendTo(target);
    //appending data to something
    

    makes more sense.


    Chaining Functions

    • It is also important to note that it makes more sense when chaining functions in each case aswell. ie. if you are already dealing with an element

    $(target).toggle().append(content);
    

    makes more sense than adding another line and vice versa.

    Resources

    • .append() (the jquery documentation)

    • .appendTo() (the jquery documentation)

    • a good blog post on the topic (see Difference between .append() and .appendTo() )

提交回复
热议问题