点击链接上的javascript弹出提醒

时间:2012-01-11 03:06:32

标签: javascript hyperlink alert confirm confirmation

点击链接后,我需要一个javascript'确定'/'取消'提醒。

我有警报代码:

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

但是我如何才能这样做只在点击某个链接时运行?

4 个答案:

答案 0 :(得分:26)

如果您不想继续,可以使用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>

答案 1 :(得分:12)

让它发挥作用,

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

答案 2 :(得分:12)

单行工作正常:

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

答案 3 :(得分: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"
    }
  });

});