javascript popup alert on link click

2019-02-06 05:24发布

I need a javascript 'OK'/'Cancel' alert once I click on a link.

I have the alert code:

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

But how do I make it so this only runs when clicking a certain link?

4条回答
Explosion°爆炸
2楼-- · 2019-02-06 05:35

You can use the onclick attribute, just return false if you don't want continue;

<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>
查看更多
姐就是有狂的资本
3楼-- · 2019-02-06 05:41

In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML

HTML:

<a id="theLink">Click Me</a>

I could use the following jQuery to hookup an event to that specific link.

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

});
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-06 05:47

Single line works just fine:

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

Adding another line with a different link on the same page works fine too:

<a href="http://stackoverflow.com/"
 onclick="return confirm('Click on another OK to continue.');">another link</a>
查看更多
淡お忘
5楼-- · 2019-02-06 05:53

just make it function,

<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>
查看更多
登录 后发表回答