2017-03-08 82 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