2011-12-30 164 views
2

我需要這個函數失敗並且不做確認,或者如果子函數返回false,則提交表單並保留在頁面上。Javascript函數返回

function doDelete() 
{ 
    if (THIS FAILS!()-STAY ON PAGE!) 
     // do something here 
if (confirm("Are you sure you want to update and then delete this hot part?")) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 
+2

該函數如何被調用? – 2011-12-30 14:39:49

+0

oncliick提交表格 – 2011-12-30 14:48:36

回答

1

從表單提交回調返回false將導致頁面不被提交。你也可以返回確認的結果,而不是使用if-else。

function doDelete() { 
    if (THIS FAILS!()-STAY ON PAGE!) { 
     // do something here 
     return false; 
    } 
    return confirm("Are you sure you want to update and then delete this hot part?"); 
} 
+0

你是男人......我知道這很簡單!...謝謝 – 2011-12-30 14:48:55

+0

沒問題!如果我已經回答了您的問題,請不要忘記加註+接受:) – 2011-12-30 14:50:58

0

您可以將功能的form當用戶試圖提交表單時調用。如果該函數返回false,則表單不會被提交,用戶將留在頁面上。

本質上講,你可以這樣做:

<script type="text/javascript"> 
    function doDelete() 
    { 
     if (THIS FAILS!()-STAY ON PAGE!) 
      return false; 
     return confirm("Are you sure you want to update and then delete this hot part?"); 
    } 
</script> 

<!-- Make doDelete the callback for this form's onsubmit. 
    When the user submits the form, doDelete will be called. 
    If doDelete returns false, the form will not be submitted 
    and the user will remain on the current page. --> 
<form onsubmit="doDelete" ... 
2
function doDelete() 
{ 
    if (THIS FAILS!()-STAY ON PAGE!) { 
     return false; 
    } else { 
     return confirm("Are you sure you want to update and then delete this hot part?"); 
    } 
} 
+0

是的......那樣做 – 2011-12-30 14:52:12

0

我假設你的HTML是:

<form method="POST" action="page.php" onsubmit="return doDelete()"> 
    ... 
</form> 

然後你的JavaScript應該是這樣的:

function doDelete() { 
    //if (THIS FAILS!()-STAY ON PAGE!) { 
     // do something here 
     return (confirm("Are you sure you want to update and then delete this hot part?")); 
    //} 
} 

像這樣的你是什麼意思? 您可以簡單地返回confirm()方法的結果,而不是執行if-else。

雖然我不明白這是什麼故障。這只是你的一般評論?如果是這樣,請將其忽略...... ;-)

+1

內嵌事件處理程序是反模式 – Raynos 2011-12-30 14:47:23

+0

這正是他如何使用它,雖然如果您閱讀他的問題。所以不要拍攝使者。 – Jules 2011-12-30 14:57:58

+0

該使者應該修復他的代碼;) – Raynos 2011-12-30 14:58:52