首页 > 解决方案 > 填充表格时向json添加按钮

问题描述

当我动态填充表格时,我试图插入一个按钮。我有正确加载表格的数据,并且可以插入按钮。当我单击按钮时,它会显示警报框以检查它是否正常工作。但是,当我尝试获取该行的第一个单元格的数据时,它会收到 $ 未定义的错误。

这是我的代码:

<?php
            $file = 'data.json';
            $data = file_get_contents($file);
            $json = json_decode($data);
            echo"<pre>";
            print_r($json);
            echo"</pre>";
        ?>
        <form method="POST" action="">
            <center><button class="btn btn-primary" name="display">Populate</button></center>
        </form>
    </div>
    <table class="table table-bordered table-example">
<thead class="alert-info">
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
    </tr>
</thead>
<tbody>
    <?php
        $url = 'data.json';
        $data = file_get_contents($url);
        $json = json_decode($data);
        
        foreach($json as $member){
    ?>
    <tr>
        <td><?php echo $member->firstname?></td>
        <td><?php echo $member->lastname?></td>
        <td><?php echo $member->gender?></td>
        <td><button class="btn btn-info button-details" onclick="myFunction()">>detalhes</button> 
 </td>
    </tr>
    <?php
        }
    ?>
</tbody>
</table>
    <div class="col-md-6">
        <?php include 'populate_json.php';?>
    </div>
</div>

<script type="text/javascript">

    
    function myFunction() {
alert("botao funciona");
        
        $(".table-example").find("tr td:first"); *this is not working
        
}

标签: javascriptphphtml

解决方案


将其包含在您的 html 头中:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

推荐阅读