2017-05-27 164 views
0

我有這個表:刪除元素

Img

下面是這個頁面的代碼:

<?php 
include('footer.php'); 
include('../models/fetchQuotes.php'); 
$content = file_get_contents("http://test/MY_API/getAllTopics"); 
$arrayId = array(); 
$arrayName = array(); 
$arrayImg = array(); 
foreach (json_decode($content, true) as $eventrType => $events) { 
    array_push($arrayId, $events[id]); 
    array_push($arrayName, $events[name]); 
    array_push($arrayImg, $events[img]); 
} 
?> 
<div class="container"> 
    <table class="table"> 
     <thead> 
      <tr> 
       <th>ID</th> 
       <th>Name</th> 
       <th>Img</th> 
       <th>Option 1</th> 
      </tr>  
     </thead> 
     <tbody> 
      <?php for ($i=0;$i<count($arrayId);$i++) { ?> 
      <tr> 
       <td><?php echo ($arrayId[$i])." "; ?></td> 
       <td><?php echo ($arrayName[$i])." "; ?></td> 
       <td><img src="<?php echo ($arrayImg[$i])." ";?>" alt="" width="75", heigth="75"></td> 
       <td> <button class="btn btn-danger" id="deleteById" value=<?= ($arrayId[$i]); ?> onclick="myFunction()">DELETE</button> 
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
         <div class="modal-dialog"> 
          <div class="modal-content"> 
           <div class="modal-header"> 
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
            <h4 class="modal-title" id="myModalLabel">Ошибка</h4> 
           </div> 
           <div class="modal-body" id ="modal-body"> 

           </div> 
           <div class="modal-footer"> 
            <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button> 
           </div> 
          </div> 
         </div> 
        </div></td> 
       </tr><?php } ?> 
      </tbody> 
     </table> 
    </div> 
    <script> 
    function myFunction(){ 
     var deleteById = document.getElementById('deleteById').value; 
     alert(deleteById); 
    } 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
    <script src="../js/bootstrap.min.js"></script> 

我分析我自己的API,然後將其填充到一個表。現在,當我點擊任何按鈕刪除,每次我有相同的警報「12」。我明白爲什麼它會發生,但我無法弄清楚如何使其正確。 如何將每個按鈕與相應的單元ID關聯? 對不起,語言錯誤,並感謝您的幫助。

回答

1

問題是,你只能在一個頁面中只有一個ID,但是當你在一個循環內給這個按鈕一個ID時,不同的元素會得到相同的ID。

要解決這個問題,你總是可以使用class。但是你根據你的方法使用這樣的東西。

<button class="btn btn-danger" onclick="myFunction(<?= ($arrayId[$i]); ?>)">DELETE</button> 

而且在JavaScript

function myFunction(id){ 
     alert(id); 
    } 

我希望這可以幫助你。

乾杯:)

+0

是的,它的作品正確。謝謝。 –

0

我勸你還是通過電流ID作爲函數參數:

<button class="btn btn-danger" value=<?= ($arrayId[$i]); ?> onclick="myFunction(<?= ($arrayId[$i]); ?>)">DELETE</button> 

和功能特徵將是:

function myFunction(idToDelete){ 
    alert(idToDelete); 
} 

而且我從button刪除id屬性,因爲它不是必需的。如果你想在未來使用多個元素相同的ID - 不要,因爲ID爲必須在html頁面上是唯一的

+0

同樣的,第一個答案。這是作品,謝謝。 –