为什么警报仅适用于第一行

Why alert works only on first row?

本文关键字:一行 适用于 为什么      更新时间:2023-09-26

我使用 Zebra 对话框,每次单击"删除"时都会尝试发出警报。仅当我单击第一行中的"删除"时,警报才有效。它下面的所有行都不起作用,我不知道为什么?

<table>              
     <tr>
        <td>Example1</td>
        <td><a id="delete" href="#">Delete</a></td>
     </tr>
        <td>Example1</td>
        <td><a id="delete" href="#">Delete</a></td>
     </tr>
        <td>Example1</td>
        <td><a id="delete" href="#">Delete</a></td>
     </tr>
</table>

<script>
$(document).ready(function(){
    $("#delete").bind("click",function(e){
        e.preventDefault();
        $.Zebra_Dialog("Do you want to delete?",{
            type : "question",
            title: "Question"
        });
    });
});
</script>

Id 必须是唯一的。这在这里造成了问题。因此,为了使您的代码正常工作,通过将其更改为类来进行一些小的更改。

将标记更改为

<table>              
     <tr>
        <td>Example1</td>
        <td><a class="delete" href="#">Delete</a></td>
     </tr>
        <td>Example1</td>
        <td><a class="delete" href="#">Delete</a></td>
     </tr>
        <td>Example1</td>
        <td><a class="delete" href="#">Delete</a></td>
     </tr></table>

然后在jquery中

<script>
  $(document).ready(function(){
     $(".delete").bind("click",function(e){  <-----  class selector
     e.preventDefault();
     $.Zebra_Dialog("Do you want to delete?",{
      type:"question",
      title:"Question"
    })
    //  send an ajax request here based up on the user selection 
  });
});
</script>

如果您是初学者,请在此处阅读标准指南。

元素

的ID属性必须是文档中的唯一值,在您的情况下,所有删除链接都具有相同的ID。如果有多个元素共享一个共同的行为,请使用公共类属性将它们组合在一起。

<table>
    <tr>
        <td>Example1</td>
        <td><a class="delete" href="#" data-id="1">Delete</a>
        </td>
    </tr>
    <tr>
        <td>Example1</td>
        <td><a class="delete" href="#" data-id="2">Delete</a>
        </td>
    </tr>
    <tr>
        <td>Example1</td>
        <td><a class="delete" href="#" data-id="3">Delete</a>
        </td>
    </tr>
</table>

然后

$(document).ready(function () {
    $(".delete").bind("click", function (e) {
        e.preventDefault();
        var $this = $(this);
        $.Zebra_Dialog("Do you want to delete?", {
            type: "question",
            title: "Question",
            buttons: ['Delete', 'Cancel'],
            onClose: function (caption) {
                if (caption == 'Delete') {
                    $.ajax({
                        url: 'delete.php',
                        data: {
                            id: $this.data('id')
                        }
                    }).done(function(){
                        $this.closest('tr').remove();
                    }).fail(function(){
                        alert('there was an error while deleting the record')
                    })
                    //code required to delete the record from server goes in here
                }
            }
        })
    });
});

演示:小提琴