简体   繁体   中英

javascript redirect does work properly

I have a link which displays a confirm box when user click on it. If the user click yes then it will lead them to the specified page, otherwise it stays on the same page. Here is my link and my function code:

<script type='text/javascript'>
   function checkDelete(){
      var i = confirm("Are you sure you want to delete?");
      if(i){
         return true;
      }else{
         return false;
      }
   }
</script>
<a href="operation.php?action=delete&id=<?php echo $id?>" onclick='checkDelete'>Delete</a>

The problem is that it does not stay on the same page even I click "No" or cancel button. It always redirect to the page operation.php. But if I write inline javascript code on the onclick even then it works fine.

You've got a few problems:

The JavaScript code checkDelete simply references the variable checkDelete ; it does nothing further. You probably meant to call it, and further, return the result of calling it:

// in onclick
return checkDelete();

Your use of if with the return statements is redundant. Simply return the result of confirm :

function checkDelete() {
    return confirm('...');
}

At this point, you could even inline it:

// in onclick
return confirm('...');

It is generally frowned upon to have inline JavaScript. It is better to bind event handlers from JavaScript. For example, if your link had an ID of delete_link , you could use this:

// should only be run when delete_link exists
// (e.g. in a DOM ready handler or a script after delete_link)
// this code does not accommodate for older versions of Internet Explorer
document.getElementById('delete_link').addEventListener('click', function(e) {
    if(!confirm('...')) {
        e.preventDefault();
    }
}, false);

Try onclick="return checkDelete();" . Using a proper JavaScript expression kind of helps when you try to use JavaScript ;)

At the same time, try changing checkDelete to this:

function checkDelete() {return confirm("Are you sure you want to delete?");}

Try:

<a href="operation.php?action=delete&id=<?php echo $id?>" onclick='return checkDelete();'>Delete</a>

<script type='text/javascript'>
   function checkDelete(){
      var i = confirm("Are you sure you want to delete?");
      if(i){
         return true;
      }else{
         return false;
      }
   }
</script>

The <a href=''> tag always redirects to the target. The concept of returning false and cancelling the operation only applies when you're submitting a form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM