为什么警报仅在第一行有效?

时间:2013-09-22 10:56:20

标签: javascript jquery

我使用 Zebra Dialog ,每次点击删除时,我都会尝试设置警报。 警报仅在我单击第一行中的删除时才起作用。它下面的所有行都不起作用,我不知道为什么?

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

2 个答案:

答案 0 :(得分: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>

如果您是初学者,请浏览standard guide here.

答案 1 :(得分:1)

元素的

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

<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
                }
            }
        })
    });
});

演示:Fiddle