![](/img/trans.png)
[英]Test if a function with multiple if/else blocks return true or false in javascript
[英]javascript function with if else statements ignore return true/false
所以我有一個用isset($_POST[])
提交的 PHP 表單。 我寫了一個 js 函數,它運行一些帶有if-else
代碼,它應該return true/false
但事實並非如此,並且無論如何都會提交表單。
我試過使用e.preventDefault()
但這對我也不起作用。 我還嘗試將 true/false 放在 var 中,因為out = true/false
(當然,我將它們放在不同的 var 中,因為 if 和 else ),然后嘗試將它們作為return out
。 var 中真/假的代碼 -
function submitFunc(a, b) {
if (a >= b) {
alert("*Duration cannot be greater than Quoted Hours");
out = false;
}
else {
out = true;
}
window.location = "add_working_details.php";
return out;
}
原始代碼 -
function submitFunc(a, b) {
if (a >= b) {
alert("*Duration cannot be greater than Quoted Hours");
// event.preventDefault();
//out = false;
return false;
window.location = "add_working_details.php";
}
else {
// out = true;
return true;
}
//return out;
// window.location = "add_working_details.php";
}
AJAX 函數——
$("#submit").click(function(){//comparing the total quoted hours with duration of time selected
ticket_id = $('#ticket_no').val();
total_hours = $('#total_hours').val();
var user_dur, ud, th;
$.ajax({
url: 'comp_time.php',
type: 'GET',
data: {ticket_id: ticket_id, total_hours: total_hours} ,
success: function (response) {
// console.log("response", response);
var resp = response;
user_dur = $('#time_duration').text();
ud = compare_time(user_dur); //user duration
th = Number(resp); //total quoted hours
submitFunc(ud, th);
}
});
});
所以我相信返回false
應該停止提交表單,然后使用window.location
它應該重定向到我想要的頁面,但它沒有這樣做。 如果我的邏輯錯誤,請糾正我。 謝謝你的時間。
首先,無論事件結果如何,您的功能都應阻止提交
$("#submit").click(function(e){
e.preventDefault();
其次,您需要從函數中刪除返回值,它們不會影響您的點擊事件
function submitFunc(a, b) {
if (a >= b) {
alert("*Duration cannot be greater than Quoted Hours");
} else {
window.location = "add_working_details.php";
}
}
$('#form').submit(function(e) {
if (submitFunc(1, 2)) {
$.ajax({});
} else {
e.preventDefault();
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.