将表行元素传递给js

时间:2017-03-08 14:54:03

标签: javascript twitter-bootstrap html-table

我有一个引导表,该数据库是从数据库加载的。 我有一个js函数从数据库中删除一个表行,所以我在表的每一行添加一个按钮。

  <table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
                      <thead>
                        <tr>
                          <th>id</th>
                          <th>client</th>
                        </tr>
                      </thead>

                      <tbody>
                         <?php
                         require("config.php");
                         // Create connection
                         $conn = new mysqli($host, $username, $password, $dbname);
                         // Check connection
                         if ($conn->connect_error) {
                             die("Connection failed: " . $conn->connect_error);
                         }

                         $sql = "SELECT * FROM users";
                         $result = $conn->query($sql);

                         if ($result->num_rows > 0) {
                             // output data of each row
                             while ($row = $result->fetch_row()) {
                                          $user_id=$row[0];
                                          $user_name=$row[1];
                                ?>

                               <tr>
                                 <!--here showing results in the table -->
                                   <td><?php echo $user_id;  ?></td>
                                   <td ><?php echo $user_name;  ?></td>

                                   <td>

                                       <input type="button" class="btn btn-danger btn-xs delete" value="Cancella sin id" onclick="deleteFunction()"/>


                                   </td>
                               </tr>

                      </tbody>
                    </table>

如何将id或user_name传递给 deleteFucntion ,以便将它们用于Javascipt,如下所示:

function deleteFunction() {

    var username = #MY_ROW_USERNAME;
    ....
}

1 个答案:

答案 0 :(得分:0)

TD应该是这样的

<td id="user_name_<?=$user_id?>" onClick="deleteFunction(<?=$user_id?>)"><?=$user_name?></td>

删除这样的功能

function deleteFunction(user_id) {
   var username = document.getElementById('user_name_'+user_id).innerHTML;
}