[英]Deleting after confirmation in php
我有聯系表。 現在,當我需要刪除一條記錄時,需要一個確認框來要求用戶確認。 到目前為止,我已經做到了。 但是該記錄將同時刪除為OK
和Cancel
按鈕。
我的代碼如下:
<td><a href="edit.php?id=<?php $_SESSION["name"] = ""; $_REQUEST["id"]=$row["first_name"]; echo $row["first_name"]; $_SESSION["name"]=$row["first_name"]; ?>">Edit</a> / <a href="delete.php?id=<?php echo $row["first_name"]; ?>" onclick="check()"> Delete </a></td>
<script>
function check(){
if(confirm("Are you sure you want to delete?")){
window.location.href = "delete.php?id=<?php echo $row["first_name"]; ?>";
return true;
}
else{
header("Location: http://localhost/test/display.php?show_details=Show+Details");
return false;
}
}
</script>
僅在單擊確認框中的“ OK
按鈕並單擊“ Cancel
返回到display.php
(同一頁)后,才可以刪除記錄嗎?
僅在單擊OK
,它應該導航到delete.php
,在單擊Cancel
,保持在display.php
。
我是PHP新手。請幫助...
HTML錨點具有默認的點擊操作:打開鏈接。 現在,如果您在JavaScript中添加另一個單擊處理程序,則必須阻止該元素的默認操作 ,從而阻止打開鏈接。
為了防止內聯事件處理程序(使用屬性onclick
進行設置而不是使用JS中的addEventListener()
中的默認事件操作,必須在該事件處理程序中返回false
。
另請參閱: 如何防止onclick方法中的默認事件處理?
以下兩個片段修復了該問題,並且也重新使用了href
-attribute,因此不得再次在JS中對其進行硬編碼。
變體1:
<p>
<a href="edit.php?id=123">Edit</a>
/
<a href="delete.php?id=123" onclick="return check(this)">Delete</a>
</p>
<script>
function check(anchor) {
/* Only open the delete-link, if the confirm returns TRUE */
if (confirm('Are you sure you want to delete?')) {
window.location.href = anchor.href;
}
/* Return FALSE to prevent the default link action */
return false;
}
</script>
變體2:
<p>
<a href="edit.php?id=123">Edit</a>
/
<!-- Return FALSE to prevent the default link action -->
<a href="delete.php?id=123" onclick="check(this); return false;">Delete</a>
</p>
<script>
function check(anchor) {
/* Only open the delete-link, if the confirm returns TRUE */
if (confirm('Are you sure you want to delete?')) {
window.location.href = anchor.href;
}
}
</script>
變型3A:
不返回false,而是使用event.preventDefault()
。 (靈感來自@ths的評論)
<p>
<a href="edit.php?id=123">Edit</a>
/
<a href="delete.php?id=123" onclick="check(event, this)">Delete</a>
</p>
<script>
function check(event, anchor) {
/* Prevent the default link action */
event.preventDefault();
/* Only open the delete-link, if the confirm returns TRUE */
if (confirm('Are you sure you want to delete?')) {
window.location.href = anchor.href;
}
}
</script>
變體3B:
不返回false,而是使用event.preventDefault()
。 (靈感來自@ths的評論)
<p>
<a href="edit.php?id=123">Edit</a>
/
<a href="delete.php?id=123" onclick="event.preventDefault(); check(this);">Delete</a>
</p>
<script>
function check(anchor) {
/* Only open the delete-link, if the confirm returns TRUE */
if (confirm('Are you sure you want to delete?')) {
window.location.href = anchor.href;
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.