2017-03-08 98 views
-1

我有一个引导表,该表元素是从数据库加载的。 我有一个js函数从数据库中删除一个表行,所以我在表的每一行中添加一个按钮。将表格行元素传递给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> 

如何传递到deleteFucntion ID或USER_NAME才能使用它们变成javascipt的是这样的:

function deleteFunction() { 

    var username = #MY_ROW_USERNAME; 
    .... 
} 
+1

如果在循环播放时将按钮添加到每一行,则可以将该ID添加到按钮的onclick中onclick =“functionDelete(id)”' – Toxide82

回答

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; 
} 
+0

这总是会得到列表中的第一个。不管你点击哪一个! – Toxide82

+0

你不应该有具有相同ID的元素?你不应该每次都有不同的id。 user_name_1,user_name_2等。如果这样结合你的评论和我的将是你需要的 – throwSmartDev

+0

,但是如果你有这个id你为什么需要这个名字......这个ID应该永远是唯一的,就像一个名字可以是一样的。 ...如果你想在数据库中引用它,ID是实现它的最好方法。 – Toxide82