JQuery确认链接仅用于列表中的第一个链接

时间:2014-02-20 20:03:50

标签: javascript jquery confirm

我有以下脚本:

<script type="text/javascript">
$(document).ready(function() {
    $('#confirm_Group_Delete').click(function(event) {
        event.preventDefault();
        if (confirm('All loan units grouped to this group will be unlinked. Are you sure you want to DELETE this group?')) {
            var url = $(this).attr('href');
            $('#content').load(url);
        }
        else
        {
            return false;
        }
    });
});
</script>

桌子上摆满了各种物品:

<td>
    Item 1 <a id="confirm_Group_Delete" href='<?=$_SERVER['PHP_SELF']?>?sec=groups&action=delete&id=<?=$group['id']?>#group'>Delete</a>
    Item 2 <a id="confirm_Group_Delete" href='<?=$_SERVER['PHP_SELF']?>?sec=groups&action=delete&id=<?=$group['id']?>#group'>Delete</a>
    Item 3 <a id="confirm_Group_Delete" href='<?=$_SERVER['PHP_SELF']?>?sec=groups&action=delete&id=<?=$group['id']?>#group'>Delete</a>
</td>

问题是JQuery确认脚本只显示列表中的第一项 - 在这种情况下为项目1.对于所有其他项目,网站删除项目而不确认。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

不同元素的id属性不能相同。

更改选择器以调用类而不是id:

<script type="text/javascript">
$(document).ready(function() {
    $('.confirm_Group_Delete').click(function(event) {
        event.preventDefault();
        if (confirm('All loan units grouped to this group will be unlinked. Are you sure you want to DELETE this group?')) {
            var url = $(this).attr('href');
            $('#content').load(url);
        }
        else
        {
            return false;
        }
    });
});
</script>

然后像这样更改你的HTML:

<td>
    Item 1 <a class="confirm_Group_Delete" href='<?=$_SERVER['PHP_SELF']?>?sec=groups&action=delete&id=<?=$group['id']?>#group'>Delete</a>
    Item 2 <a class="confirm_Group_Delete" href='<?=$_SERVER['PHP_SELF']?>?sec=groups&action=delete&id=<?=$group['id']?>#group'>Delete</a>
    Item 3 <a class="confirm_Group_Delete" href='<?=$_SERVER['PHP_SELF']?>?sec=groups&action=delete&id=<?=$group['id']?>#group'>Delete</a>
</td>