JavaScript弹出警告框在链接点击时

23
我需要在单击链接后弹出一个 JavaScript “确定”/“取消”提示框。
我已经有了警报代码:
<script type="text/javascript">
<!--
var answer = confirm ("Please click on OK to continue.")
if (!answer)
window.location="http://www.continue.com"
// -->
</script>

但是我该如何使它只在点击特定链接时运行?

4个回答

32

你可以使用 onclick 属性,如果你不想继续执行,只需return false;

<script type="text/javascript">
function confirm_alert(node) {
    return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>

这实际上运行得更好 - 更通用的解决方案应该被接受。 - jave.web

20

单行就可以正常工作:

<a href="http://example.com/"
 onclick="return confirm('Please click on OK to continue.');">click me</a>

在同一页面上添加另一行具有不同链接的内容也可以正常工作:

<a href="http://stackoverflow.com/"
 onclick="return confirm('Click on another OK to continue.');">another link</a>

18

只需要让它运行起来即可。

<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>

<a href="javascript:AlertIt();">click me</a>

@user1022585,你需要使用return false来阻止链接跳转。请看下面的答案 - Confirm方法返回一个布尔值,你可以用它来退出函数... - Alex
抱歉我复制了你的代码,但是你的代码有误。如果用户说“好的”,答案将会被设置为“true”,因此我们不需要“!”,我已经修改了它。 - Okan Kocyigit
通过JavaScript打开空白弹出窗口:jswin = window.open("", "test-window", "width=350,height=150"); - iltaf khalid
我在我的HTML中有多个href标签,我想为每个单独的链接执行不同的警报弹出,那么我如何知道JavaScript是从哪个链接访问的? - Nischaya Sharma
1
@NischayaSharma,请查看@muzuiget的答案。你不能在href中传递this。你应该使用onclick,并传递参数this - Okan Kocyigit

4
为了实现这一功能,您需要将处理程序附加到页面上特定的锚点。对于此类操作,使用标准框架如jQuery更加容易。例如,如果我有以下HTML代码:
<a id="theLink">Click Me</a>

我可以使用以下 jQuery 将事件与该特定链接连接起来。
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {

  // The '#theLink' portion is a selector which matches a DOM element
  // with the id 'theLink' and .click registers a call back for the 
  // element being clicked on 
  $('#theLink').click(function (event) {

    // This stops the link from actually being followed which is the 
    // default action 
    event.preventDefault();

    var answer confirm("Please click OK to continue");
    if (!answer) {
      window.location="http://www.continue.com"
    }
  });

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接