-2

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

<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>
4

2 回答 2

4

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>

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

于 2013-09-22T10:57:12.920 回答
1

元素的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
                }
            }
        })
    });
});

演示:小提琴

于 2013-09-22T10:57:36.613 回答