简体   繁体   中英

Optimize way to append element in html using jquery

What is the optimize way to append this element to my specific DIV Class using JQUERY. This will generate dynamic elements. I use .AppendTo then display dynamically the element inside <div class='parent-list-workorder'> .

Here's my code so far but it doesn't work:

$(document).ready(function(){

    var ListOfWorkOrders = [];

    $("#button").click(function(){

        //var _WOID = $('.list-workorder-id').text();

        var _WOID = $('#txtWOID').val();

        //alert(_WOID);

        $.ajax({
          url:'getWorkOrders.php',
          type:'POST',
          data:{id:_WOID},
          dataType:'json',
          success:function(output){


            for (var key in output) {

                if (output.hasOwnProperty(key)) {

                    $("<div class='child-list-workorder'>

                        <div class='list-workorder'>

                            <div class='list-workorder-header'>

                                <h3 class='list-workorder-id'>" + output[key] + "</h3>

                            </div>

                            <p>" + Sample + ":" + key + "</p>

                        </div>

                    </div>").appendTo("<div class='parent-list-workorder'>");

                    //alert(output[key]);

                }
            }

            console.log(output);              

          }

        });

    });

});

Am I missing something?

Your problem is in the code below:

.appendTo("<div class='parent-list-workorder'>");

The parameter of appendTo() should also be a valid selector.

you can try this instead:

.appendTo("div.parent-list-workorder");

granting that div.parent-list-workorder already exists.

You have two problems. First, you need to use a selector as an argument to .appendTo() , not an HTML string. Second, you need to remove or escape the newlines in the HTML string.

$("<div class='child-list-workorder'>\
     <div class='list-workorder'>\
       <div class='list-workorder-header'>\
         <h3 class='list-workorder-id'>" + output[key] + "</h3>\
       </div>\
       <p>" + Sample + ":" + key + "</p>\
    </div>\
 </div>").appendTo("div.parent-list-workorder");

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