简体   繁体   中英

Jquery appendTo() appends the element two times

I have a little script that creates a table hover a div, this script creates the <tr> and <td> dynamically depends of the width and height of the <div> this is executed from a for sentence but the appendTo is executed two times, in the next image we can see that the attributes and id that I put in the elements is duplicated and this attribute corresponds at the value of the "for" variable.

This is my complete page:

 <!doctype html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="styles.css"> <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script> </head> <body> <div id="content-map"> <img id="main-reference" src="puestos.png" style="display: none; visibility: hidden"/> </div> </body> <script> var table = '<table id="grilla" cellspacing="0" cellpadding="0"></table>'; var tr = '<tr id="current-row"><tr>'; var td = '<td><td>'; var maxHeight = 1200; var maxWidth = 700; var height = $( "#main-reference" ).get( 0 ).naturalWidth; var width = $( "#main-reference" ).get( 0 ).naturalHeight; if ( maxHeight > height && maxWidth > width ) { $( "#content-map" ).css( { "width": width, "height": height } ); } else { $( "#main-reference" ).css( { "display": "block" } ); $( "#content-map" ).css( { "width": $( "#main-reference" ).width(), "height": $( "#main-reference" ).height() } ); } var finalHeight = $( "#content-map" ).height(); var finalWidth = $( "#content-map" ).width(); var numberOfRows = Math.floor( finalHeight / 30 ); var numberOfCols = Math.floor( finalWidth / 30 ); var tdHeight = finalHeight / numberOfRows; $( "#main-reference" ).css( { "display": "none" } ); $( table ).appendTo( "#content-map" ); for ( var i = 0; i <= numberOfRows; i++ ) { $( tr ).appendTo( "#grilla" ).attr( "row-number", i ); for ( var j = 0; j <= numberOfCols; j++ ) { console.log( "numberOfCols[" + numberOfCols + "]" + ":" + j ); $( td ).appendTo( "#current-row" ).css( { "height": tdHeight } ).attr( "id", j ); } $( "#current-row" ).removeAttr( "id" ); } </script> </html> 

and results in :

在此处输入图片说明

you need to close the tr and td elements :

var tr = '<tr id="current-row"></tr>';
var td = '<td></td>';

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