问题
This is script what I have currently -
<script type="text/javascript">
$(document).ready(function () {
$('.RemoveSystem').click(function () {
var href = $(this).attr('href');
var answer = confirm("Are you sure you want to delete this system?");
alert(answer);
if (answer)
window.location = href;
});
});
</script>
Here is the link which is there for each record and we can delete each system when we click on its delete button -
<%= Html.ActionLink("Delete", "RemoveSystem", new { SysNum = item.Id}, new { @class = "RemoveSystem" })%>
Now here is the problem the actionlink redirects no matter what happens and I need to stop it. I mean say the user presses cancel on the confirm the actionlink still executes and goes to RemoveSystem Action, where I want it to just stay on the page.I thought of using a HTML hyperlink but I dont know how I should pass id the value to the javascript in that case. Can anyone please help me out ?
回答1:
You need to prevent the default action of the link like this:
$('.RemoveSystem').click(function () {
if (confirm("Are you sure you want to delete this system?"))
window.location = $(this).attr('href');
return false;
});
Or this:
$('.RemoveSystem').click(function (e) {
if (confirm("Are you sure you want to delete this system?"))
window.location = $(this).attr('href');
e.preventDefault();
});
Currently, the link is doing this function but also doing what it does with no JavaScript at all, which is to go to the href
it has...that's the behavior you need to prevent from happening.
回答2:
Return false if you want to prevent the default action:
$('.RemoveSystem').click(function () {
var href = $(this).attr('href');
var answer = confirm("Are you sure you want to delete this system?");
if (answer)
window.location = href;
return false;
});
or use preventDefault:
$('.RemoveSystem').click(function (evt) {
var href = $(this).attr('href');
var answer = confirm("Are you sure you want to delete this system?");
if (answer)
window.location = href;
evt.preventDefault();
});
回答3:
In your script function add:
if (answer)
window.location = href;
else
return false;
来源:https://stackoverflow.com/questions/3619214/how-do-i-stop-an-actionlink-redirect-and-instead-popup-and-redirect-using-javasc