按钮仅适用于第一行

时间:2018-08-05 08:27:35

标签: php laravel laravel-5

我已经在表的EDIT列中放置了按钮,但是该按钮仅对第一行单击事件有效。我试图在单击按钮时打开弹出窗口。仅在单击第一行按钮时打开弹出窗口。

<tbody>
    @foreach($books as $data)
     <tr>
         <td> {{$data['BookID']}} </td>
         <td> {{$data['BookName']}} </td>
         <td> {{$data['BookUnitPrice']}} </td>
         <td><button type="button" value="EDIT" style="height:20px;" id="myBtn"></button></td>
         <td> {{$data['BookUnitPrice']}} </td>
     </tr>
    @endforeach
</tbody> 

javascript代码

<script>
    var modal = document.getElementById('myModal');

    // Get the button that opens the modal
    var btn = document.getElementById("myBtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal 
    btn.onclick = function() {
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>

2 个答案:

答案 0 :(得分:1)

您已经创建了多个具有相同ID的按钮,这实际上是不允许的,因为该ID是元素的唯一标识符。您可以为每个按钮分配自己的唯一ID,然后再听所有按钮,但最简单的方法是监听事件冒泡:

<tbody id="button-parent">
    @foreach($books as $data)
     <tr>
         <td> {{$data['BookID']}} </td>
         <td> {{$data['BookName']}} </td>
         <td> {{$data['BookUnitPrice']}} </td>
         <td><button type="button" value="EDIT" style="height:20px;"></button></td>
         <td> {{$data['BookUnitPrice']}} </td>
     </tr>
    @endforeach
</tbody>

JavaScript

<script>
    var modal = document.getElementById('myModal'); //I am assuming that this actually is unique
    var btnContainer = document.getElementById("button-parent");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal 
    btnContainer.onclick = function(e) {
        modal.style.display = "block";
        // if you need to know which button was pressed then it's e.target
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>

答案 1 :(得分:-1)

在javascript(jquery)中选择表并循环遍历所有表行。然后添加单击该按钮的事件侦听器并执行所需的任何操作。

$('table tr').each((i,element), () => {
  $(`${element} td button`).click(() => {
    // perform any action you want
  });
});