点击时如何更改表格中的单元格值?

时间:2019-06-23 13:58:29

标签: javascript php html

我的任务是创建一个从1到10的数字的乘法表,其中包含这些数字的所有可能组合,并且当单击其中一种可能性时,应更改单元格并输出结果。 例如,当您单击2 x 4时,单元格将更改为8。 单击时,还应该将数据发送到数据库,包括两个因素,即单击单元格的结果和日期。

我设法创建了一个表,并尝试在单元格上添加onclick事件,如代码所示,但这是行不通的。甚至有可能在php中做到这一点,还是我需要包含javascript?

<html>
<link href="styles.css" rel="stylesheet" type="text/css">
<head>
</head>
<body>
<?php
function changeCell($row,$col){
    echo $row*$col;
}
?>
<table table border =\"1\" style='border-collapse: collapse'  class='style'>
    <thead>
        <tr>
            <th></th>
            <?php for($j=1;$j<=10;$j++)
            {
                ?>
            <th><?php echo $j; ?></th>
            <?php
            }
            ?>
        </tr>
    </thead>
    <tbody>
        <tr>
        <?php 
        for($i=1;$i<=10;$i++)
        { echo "<tr> \n";
        ?>
            <td><?php echo $i;?></td>
        <?php
            for ($j=1;$j<=10;$j++)
            {
        ?>
            <td onclick = 'changeCell($i,$j)'><?php echo $i." x ".$j; ?></td>
        <?php
        }
        ?>
        <?php
        }
        ?>
        </tr>
    </tbody>
    </table>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

一个简单的演示,用于说明事件处理以及使用ajax将信息发送到db /后端。

如上面的注释中所述:PHP在服务器上运行,并且将在浏览器最终加载页面之前完成所有任务,因此您需要触发希望响应用户操作执行的任何PHP函数在另一个线程中。这通常是使用ajax / fetch实现的。

<?php
    /* set size of table */
    $rows = $columns = 12;


    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        $_POST['db']='updated';
        exit( json_encode( $_POST ) );
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <script>
            document.addEventListener('DOMContentLoaded',e=>{

                /* a rudimentary ajax function for performing POST requests */
                const ajax=function(url,params,callback){
                    let xhr=new XMLHttpRequest();
                    xhr.onload=function(){
                        if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
                    };
                    xhr.onerror=function(e){
                        alert(e)
                    };
                    xhr.open( 'POST', url, true );
                    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
                    xhr.send( params );
                };

                /* A very basic callback function */
                const ajaxcallback=function(r){
                    document.querySelector('output').innerText=r
                }

                /*
                    scan the DOM to find all table cell elements with assigned class "multiplication"
                    and assign an event listener to each.

                    The event listener listens for clicks, captures certain dataset attributes from the
                    event target ( cell ) and performs the calculation using the numbers found.

                    The ajax function sends a querystring to the backend PHP script for processing - that
                    part has not been done here.

                    The clicked table cell will reflect the answer temporarily before reverting to it's original
                    value.
                */
                Array.prototype.slice.call( document.querySelectorAll('table td.multiplication') ).forEach( cell=>{
                    cell.addEventListener('click',function(e){

                        let challenge=this.innerText;
                        let product=this.dataset.row * this.dataset.column;

                        ajax.call( this, location.href, 'task=multiplication&challenge='+challenge+'&a='+this.dataset.row+'&b='+this.dataset.column+'&product='+product, ajaxcallback )

                        console.info( 'Challenge: %s Row: %s Column: %s Answer: %d',challenge, this.dataset.row, this.dataset.column, product );

                        this.innerText=product;
                        this.classList.add('product');

                        setTimeout( function(e){
                            this.innerText=challenge;
                            this.classList.remove('product');
                        }.bind( cell ), 2500 );
                    })
                })
            });
        </script>
        <style>
            body, body *{box-sizing:border-box;font-size:0.9rem;font-family:calibri,verdana,arial}
            body{padding:0;margin:0;}
            table{background:azure;}
            table{width:80%;height:80vh;border:1px solid black;float:none;margin:auto;}
            td{text-align:center;margin:1px;background:white}
            td.multiplication{border:1px dotted gray;cursor:pointer;}
            th,td.rowheader{background:gray;color:white;}
            .product{background:rgba(0,255,0,0.1)}
            output{display:block;float:none;margin:auto;width:80%;padding:0.5rem;text-align:center; color:red }
        </style>
    </head>
    <body>
        <form method='post'>
            <table>
                <tr>
                <?php
                    for( $i=0; $i <= $columns+1; $i++ ){
                        if( $i > 0 )printf("<th scope='col' data-column=%d>%d</th>", $i-1, $i-1 );
                    }
                ?>
                </tr>
                <?php
                    for( $i=1; $i <= $rows; $i++ ){
                        echo "<tr data-row=$i>";

                        for( $j=0; $j <= $columns; $j++ ){
                            if( $j > 0 )printf("<td class='multiplication' data-row=%d data-column=%d>%d x %d</td>",$i,$j,$i,$j);
                            else printf("<td class='rowheader'>$i</td>");
                        }

                        echo "</tr>";
                    }
                ?>
            </table>
            <output></output>
        </form>
    </body>
</html>