在Javascript确认对话框之后,网页将转到顶部.如何阻止这种情况

After Javascript confirm dialog, web page goes to top. How to stop this?

本文关键字:顶部 何阻止 情况 确认 Javascript 对话框 之后 网页      更新时间:2023-09-26

我使用确认对话框来确认是否从页面中删除一些元素。那部分很好用。问题是,单击"确认"或"取消"后,页面会滚动到顶部。我该如何阻止这种行为?

$('.deleter').click(function () {
    if (confirm('Do you want to remove' + $(this).attr('name') + '. This action can not be undone.')) {
        $('.g' + $(this).attr('itemId')).remove();
        $('.' + $(this).attr('itemId')).remove();
    }
});

如果做不到这一点,将窗口设置回以前的空间就可以了。

编辑:HTML代码

<a href='#' class='deleter' name='eg' itemId='4'>delete</a>

感谢阅读

它实际上是跳到位置#a的默认行为)。您需要通过preventDefault()来防止这种默认行为。

试试这个,

$('.deleter').click(function (e) {
    e.preventDefault();
    if (confirm('Do you want to remove' + $(this).attr('name') + '. This action can not be undone.')) {
        $('.g' + $(this).attr('itemId')).remove();
        $('.' + $(this).attr('itemId')).remove();
    }
});
动画是正确的。你的链接告诉它转到页面顶部:
<a href='#' class='deleter' name='eg' itemId='4'>delete</a>

如果你不想你的链接像一个真正的锚链接,那么:

a。不要把它作为链接。将点击事件绑定到不同类型的对象(如按钮)

b。给href一个适当的null值,例如javascript:

 <a href='javascript:;' class='deleter' name='eg' itemId='4'>delete</a>

听起来像是将事件绑定到一个锚点元素,其默认行为是导致对资源的GET。以下将阻止锚点的默认行为:

$('.deleter').click(function (e) { 
    e.preventDefault();
    if (confirm('Do you want to remove' + $(this).attr('name') + '. This action can not be undone.')){
    $('.g' + $(this).attr('itemId')).remove();  
    $('.' + $(this).attr('itemId')).remove();
    } 
});

或者:

$('.deleter').on('click', function (e) {
    e.preventDefault();
    if (confirm('Do you want to remove' + $(this).attr('name') + '. This action can not be undone.')){
    $('.g' + $(this).attr('itemId')).remove();  
    $('.' + $(this).attr('itemId')).remove();
    } 
});

这是因为锚标记。像这样更改锚点标签**href="#_"**

<a href='#_' class='deleter' name='eg' itemId='4'>delete</a>

Confirm、Alert和Prompt实际上是依赖于浏览器的功能。我们无法改变它的行为或设计。或者,您希望将jquery插件用于对话框,而不是这些对话框。参考此,http://labs.abeautifulsite.net/archived/jquery-alerts/demo/