2017-05-27 162 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

同样的,第一个答案。这是作品,谢谢。 –