Javascript 使用php按钮按id从表中删除元素
我有这张桌子: 以下是本页的代码:Javascript 使用php按钮按id从表中删除元素,javascript,php,jquery,html,Javascript,Php,Jquery,Html,我有这张桌子: 以下是本页的代码: <?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, tr
<?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">×</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关联?
抱歉出现语言错误,感谢您的帮助。我建议您将当前ID作为函数参数传递:
<button class="btn btn-danger" value=<?= ($arrayId[$i]); ?> onclick="myFunction(<?= ($arrayId[$i]); ?>)">DELETE</button>
我还从按钮中删除了id属性,因为它不是必需的。如果您想在将来对多个元素使用相同的id,请不要这样做,因为id在html页面上必须是唯一的。问题是,在一个页面中只能有一个id,但当您在循环中为该按钮提供id时,不同的元素会获得相同的id 要解决此问题,可以始终使用类。但根据你的方法,你可以使用这样的东西
<button class="btn btn-danger" onclick="myFunction(<?= ($arrayId[$i]); ?>)">DELETE</button>
我希望这对你有帮助
干杯:只使用一个功能。不是两个。
<button class="btn btn-danger" onclick="myFunction(<?= ($arrayId[$i]); ?>)">DELETE</button>
function myFunction(id){
alert(id);
}