2012-01-11 161 views
17

我需要一个JavaScript'确定'/'取消'警告一旦我点击一个链接。javascript弹出警告链接点击

我有报警代码:

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

但我怎么做起来很点击某个链接时,这只奔跑?

回答

10

只是令其功能,

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

感谢,如果我点击取消尽管它仍然打开链接/ – user1022585 2012-01-11 03:13:44

+0

@ user1022585您需要返回false来停止链接导航。看到我的回答下面 - 确认'方法返回一个'布尔',你可以退出你的功能... – xandercoded 2012-01-11 03:18:38

+0

对不起,我复制你的代码,并且你的代码是错误的。如果用户说“好”,答案将设置为“真”,因此我们不需要“!”,我改变了它。 – ocanal 2012-01-11 03:21:57

3

为了做到这一点,你需要将处理程序附加到页面上的特定锚。对于像这样的操作,使用标准框架如jQuery要容易得多。例如,如果我有以下HTML

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

}); 
25

可以使用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> 
+0

这实际上工作得更好 - 应该接受的更一般的解决方案。 – 2014-02-01 10:57:39

11

单线工作得很好:

<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> 
0
function alert() { 
    var answer = confirm ("Please click on OK to continue.") ; 

    if(answer){ 
     window.location="url"; 
    } 
} 
+1

为了提高响应质量(这样做,不被标记),你可以解释他的代码为什么不起作用。有时候,单词有助于编码。 – 2015-09-10 19:58:03