gpt4 book ai didi

javascript - Jquery appendTo() 将元素追加两次

转载 作者:行者123 更新时间:2023-11-28 15:04:38 24 4
gpt4 key购买 nike

我有一个小脚本,可以创建一个将鼠标悬停在 div 上的表格,该脚本创建 <tr><td>动态取决于 <div> 的宽度和高度这是从 for 语句中执行的,但 appendTo 执行了两次,在下图中我们可以看到我放入元素中的属性和 id 是重复的,并且该属性对应于“for”变量的值。

这是我的完整页面:

<!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>

结果:

enter image description here

最佳答案

您需要关闭 trtd 元素:

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

关于javascript - Jquery appendTo() 将元素追加两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39622298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com