2013-05-13 74 views
-1
<script> 
      function checkName(){ 
       var tmpName = document.getElementById("name"); 
       if(tmpName.value.length == 0){ 
        alert("Name cannot be empty"); 
        return false; 
       } 
       else 
        return true; 
      } 


      function confirmForm(formObj){ 
       var nameBool = new Boolean(); 
       var errorName = ""; 


       nameBool = checkName(); 

       if(nameBool == false) 
        errorName = "Invalid data in input name !"; 

       return window.alert("You have this error : \n " + errorName + "\n" + errorID); 
      } 

</script> 
<form name=reviewform onsubmit="return confirmForm(reviewForm)" method=POST > 
      <p>Name : <input type="text" id="name" ></p> 

      <p>ID : <input type="text" id="id" ></p> 

      <input type="submit" value="Click here!"> 
</form> 

我的問題是爲什麼我的函數無法運行?沒有錯?任何資深人士都可以教我哪裏我錯了嗎?在javascript的主函數中調用另一個函數

我已經editited並加上窗體名稱和它是如何工作

我不知道這個功能是不是我的錯實現或者什麼

+1

什麼功能不運行?你怎麼知道它不運行?你怎麼試圖調試它? – 2013-05-13 14:26:29

+0

在給出的這段代碼中,你只是定義了兩個函數,而不是調用它們中的任何一個。你可以再詳細一點嗎 ? – 2013-05-13 14:27:32

+0

在Firefox,Chrome,Safari的錯誤控制檯中發生了錯誤消息嗎? – reporter 2013-05-13 14:27:56

回答

1

兩個功能,但他們需要一些工作,你顯然需要刷上你的JS知識,可以運行,你只需要打電話給他們。就目前而言,你已經定義了2個函數。沒有其他的。

其他問題,線/線:

//second line: 
var tmpName = document.getElementById("name"); 

在這裏,你不能確定這個元素已經含鉛,也許DOM還沒有準備好,所以一定要小心,只是包裝你的整個代碼在處理程序中:

window.onload = function() 
{ 
    //your code here, this gets executed after the page is fully loaded 
}; 

接下來,don't think of JS as some sort of Java-for-browsers, it's a completely different animal。這樣的東西:

var nameBool = new Boolean(); 
var errorName = ""; 

最好寫成聲明變量,但沒有分配任何東西:

var nameBool, errorName; 

如果你想確保nameBool是一個布爾值,只是分配如下所示:

nameBool = !!checkName();//double bang 

它也看起來像你試圖驗證表單或處理提交事件的種類。爲什麼不使用addEventListener呢?或者,如果你堅持:

document.getElementById('formId').onsubmit = function(e) 
{ 
    //get event object: 
    e = e || window.event; 
    //this references form, as does (e.target || e.srcElement), you can access the elements it contains, and check them one by one 
}; 
相關問題