简体   繁体   中英

why append the element to the end

I'm trying make a form with jquery/ajax

Here what I am doing:

    var form="<form id='frm'>name: <input type='text' id='name' name='name' /> <br />";
    $("#productos").append(form);

    $.get("bb.php").done(function (data){
          $("#frm").append(data); // this return a select
    });

    $("#frm").append("<p id='a1'>aa</p>");
    $("#productos").append("</form>");

I was expecting this:

<form id="frm">
    name: <input id="nombre" type="text" name="name"></input>
    <select> … </select>
    <p id="a1"> … </p>
</form>

But this is what I get:

    <form id="frm">
        name: <input id="nombre" type="text" name="name"></input>
        <p id="a1"> … </p>
        <select> … </select>        
    </form>

I know I could use insertbefore, but I would like to know why this happens, and if there is another way to fix

Because your callback, which you are specifying here -

$.get("bb.php").done(function (data){
      $("#frm").append(data); // this return a select
});

executes after you get a response from the server, while -

$("#frm").append("<p id='a1'>aa</p>");

this line executes immediately after your ajax request fires, before you receive a response. As a result, your paragraph is appearing before your select .

If you want to maintain the order, then do it like this -

$.get("bb.php").done(function (data){
    $("#frm").append(data); // this return a select
    $("#frm").append("<p id='a1'>aa</p>"); // now append the paragraph
});

or -

$.get("bb.php").done(function (data){
    $(data).insertBefore('#a1'); // this return a select
});

$("#frm").append("<p id='a1'>aa</p>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM