簡體   English   中英

Javascript:如何調用具有參數的函數

[英]Javascript: How do you invoke a function which has parameters

作為驗證onsubmit函數的一部分,我希望函數isFilled(var str)被調用。 但是,它無法成功調用,因此validateForm()函數過早終止。

<script type = "text/javascript">
function validateForm(){
    ...
    alert(isFilled("bla bla bla"));
    ...
}

function isFilled(var str){ // checks that the given string isn't empty
    if(str == "" || str == " "){
        return false;
    }else{
        return true;
    }
}
</script>

而且,瀏覽器的控制台沒有通知我該錯誤。 我應該將代碼包裝在try / catch語句中嗎? 如果是這樣,怎么辦?

在JavaScript中聲明函數參數不正確。 更正的代碼:

function isFilled(str){ // checks that the given string isn't empty
  if(str == "" || str == " "){
      return false;
  }else{
      return true;
  }
}

您正在嘗試在函數參數中聲明變量。 只要給它一個參數名

您可以將str命名為:

function isFilled(parameter){ // checks that the given string isn't empty
    if(parameter == "" || parameter == " "){
        return false;
    }else{
        return true;
    }
}

暫無
暫無

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

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