簡體   English   中英

函數返回假甚至條件為真為什么?

[英]Function is returning false even the condition is true why?

function checkform(for1)
{ 
   var result=checkform1(for1);
   alert(result);
}
function checkform1(form)
{
    var valid=false;
    var val1 = document.getElementById('security_code').value;
    $.get(url, function(data) {
        if(data.toString()==val1.toString())
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'hidden';
            valid=true;
        }
        else
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'visible';
            valid=false;
        }           
    }); 
    return valid;
}

結果警報始終為false,即使條件(data.toString()== val1.toString())為true,控件如何通過它傳遞。 thnks ..

默認情況下,$。get aka Ajax.get是異步的(它在后台運行)。 因此,您的函數“ checkform1”將在Ajax請求完成並設置“ valid”變量之前返回。

不要使用toString()作為字符串。 toString()將返回string 只是測試data == val1

您正在進行異步調用,因此如果要檢查結果,則必須在回調中執行此操作

 function checkform1(form)
{
    var valid=false;
    var val1 = document.getElementById('security_code').value;
    $.get(url, function(data) {
        if(data.toString()==val1.toString())
        {
        var elem = document.getElementById("captchaerr");
        elem.style.visibility = 'hidden';
        valid=true;
        }
        else
        {
        var elem = document.getElementById("captchaerr");
        elem.style.visibility = 'visible';
        valid=false;
        }      
        //here you will get the valid and 
        //not outside...outside it will be always false.
    }); 

    //This line will be executed immediately after the previous line
    // and will not wait for the call to complete, so this needs to be done 
    // in the callback. 
    return valid;

}

如果您的“ get” ajax調用是異步調用,則可以使用回調來獲取結果:

function checkform(for1)
{ 
   checkform1(for1, function(result) //provide the callback to the async function
   {
     alert(result); 
   });      
}
function checkform1(form, callback)
{
    var valid=false;
    var val1 = document.getElementById('security_code').value;
    $.get(url, function(data) 
    {
        if(data.toString()==val1.toString())
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'hidden';
            valid=true;
        }
        else
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'visible';
            valid=false;
        }           
        if(callback)
            callback(valid);// call the callback INSIDE of the complete callback of the 'get' jquery function
    }); 

}

在條件之前,將Alert放在兩個值alert(val1 +'---'+ data)上,看看其是否完全相同。

在比較之前也要修剪它們,以防萬一有一些填充。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM