Javascript 如何确认href标签中链接的导航?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13583415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:24:35  来源:igfitidea点击:

How to confirm navigation for a link in a href tag?

javascripthtml

提问by mirza

I'm using simple links for an admin panel but in case of user accidently clicks on link for user deletion, there should be a confirmation pop-up for avoding this.

我正在为管理面板使用简单的链接,但如果用户不小心点击了链接以进行用户删除,则应该有一个确认弹出窗口来避免此操作。

Probably as you know a href tag's are not fully compatible with javascript. So, i have used span tag for "onclick" but that didn't went so well:

可能如您所知,href 标签与 javascript 不完全兼容。所以,我已经将 span 标签用于“o​​nclick”,但效果不佳:

<script type="text/javascript">
function confirm_click()
{
return confirm("Are you sure ?");
}

</script>

Here is the html code for link:

这是链接的html代码:

   <span onclick="confirm_click();">    <a title="Delete User" href="http://www.google.com"><i class="icon-remove-sign">DELETE</i></a></span>

回答by MadSkunk

Try...

尝试...

<a title="Delete User" onclick="return confirm_click();" href="http://www.google.com"><i class="icon-remove-sign">DELETE</i></a>

...instead.

...反而。

You need to returnthe value of your method, and returning false in an onclick event prevents the default behaviour (which in this case would be to navigate to the href).

您需要返回方法的值,并且在 onclick 事件中返回 false 会阻止默认行为(在这种情况下将导航到 href)。

回答by lostsource

Try

尝试

<a href='/path/to/action' onclick="return confirm('Are you sure ?')">Delete</a>

回答by Rex Huang

Here is my code:

这是我的代码:

<a title="Delete User" id="delete" href="http://www.google.com"><i class="icon-remove-sign">DELETE</i></a>
<script type="text/javascript">
document.getElementById('delete').onclick = function(e){
    if( !confirm('Are you sure?') ) {
        e.preventDefault();
    }
}
</script>

and I think we avoid using 'onclick' and so on in HTML in order to make HTML and JavaScript separate

我认为我们避免在 HTML 中使用“onclick”等,以便将 HTML 和 JavaScript 分开

回答by SaidbakR

<body onunload="return confirm_click()">

When the page is going to be unloaded your confirm message is prompted

当页面将被卸载时,系统会提示您确认消息

A resource about unload event: http://www.w3schools.com/jsref/event_onunload.asp

关于卸载事件的资源:http: //www.w3schools.com/jsref/event_onunload.asp

回答by DonCallisto

This javascript will do the job

这个 javascript 将完成这项工作

function confirmDelete(delUrl) 
    {
        if (confirm("Sample message")) 
        {
            document.location = delUrl;
        }
    }

Obviously you have to assing it to

显然你必须将它归为

<a href="javascript:confirmDelete('yourPath')">Delete</a>