重置表并阻止表复制

Reseting table and stopping table from replicating

本文关键字:复制      更新时间:2023-09-26

每次退出页面并返回时,都会打印另一个表。点击"点击这里"按钮,然后点击返回按钮,然后再次点击"点击这里"查看问题。我想防止每次在两个页面之间来回切换时,代码都打印一个表。我还想重新摆桌子。如果你点击一个单元格,它会改变颜色,如果你在页面上来回移动,单元格仍然是白色的。我缩短了代码,以便更容易找到问题。

代码:

Js和jQuery:

$(document).ready(function() {
    $('.page2').hide();
    $('#click').click(function() {
        $('.page1').hide();
        $('.page2').show();
        function generateGrid( rows, cols ) {
            var grid = "<table>";
            for ( row = 1; row <= rows; row++ ) {
                grid += "<tr>"; 
                for ( col = 1; col <= cols; col++ ) {      
                    grid += "<td></td>";
                }
                grid += "</tr>"; 
            }
            return grid;
        }
        $( "#tableContainer" ).append( generateGrid( 10, 10) );
        $( "td" ).click(function() {
            var index = $( "td" ).index( this );
            var row = Math.floor( ( index ) / 5) + 1;
            $( this ).css( 'background-color', 'white' );
        });
        $('.back').click(function(){
            $('.page2').hide();
            $('.page1').show();
        });
    });
});
HTML:

<html>
    <head>
        <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <title>Tic-Tac-Toe Pro</title>
    </head>
    <body>
        <div class="page1">
            <p id="click">click here</p>
        </div>
        <div class="page2">
            <div class="back">
                <img src="https://i.stack.imgur.com/Fw96Z.png">
            </div>
            </br>
            <span></span>
            <div id="tableContainer"></div>
        </div>
    <script type='text/javascript' src='app.js'></script>
    </body>
</html>
CSS:

    .page1 {
            font-family:Calibri;
            height: 100%;
            width:100%;
    }
    div{
            display:inline-block;
    }
    #click{
            position:absolute;
            background-color:Yellow;
            width:300px;
            height:100px;
            cursor: pointer;
            font-size: 50;
    }
    .back{
            margin-top: 10px;
            margin-left:10px;
            cursor: pointer;
    }
    img{
            width:20%;
    }
    .page2 {
            background-color: #B9D7D9;
            height: 100%;
            width:100%;
    }
    td {
            border: 1px solid;
            width: 25px;
            height: 25px;
    }
    table {
           border-collapse: collapse; 
    }

问题行是这样的:

$( "#tableContainer" ).append( generateGrid( 10, 10) );

append函数只是将新内容添加到tableContainerdiv中已经存在的内容的末尾。

改成

$( "#tableContainer" ).html( generateGrid( 10, 10) );

并且该div的内容每次都会被完全替换