2015-05-02 40 views
1

在以下代碼中,如何基於成功的addLoadEvent(check_email)同步調用do_something() ?圍繞它在 if(){}不起作用。我需要使用Event/EventListener嗎?如果是這樣,怎麼樣?如何根據表單域檢查來協調Javascript方法調用?

的index.html:

<!DOCTYPE html > 
<html> 
<head> 
<script type="text/javascript" src="foo.js"></script> 
</head> 

... 
<form action="#"> 

<label for="email">Enter email address <img src="email.gif" alt="" /></label> 
    <input class="email_class" id="email" value="" /> 

... 
<input type="submit" value="Submit"> 
</form> 
</html> 

foo.js:

function check_email() 
{ 
    in_Forms = document.getElementsByTagName("form"); 
    for (var i = 0; i < in_Forms.length; i++) 
    { 
     in_Forms[i].onsubmit = function() 
     { 
      return check_this_email(this); 
     } 
    } 
} 

function check_this_email(some_email) { 
    var ret_val = false; 
    var in_Inputs; 

    in_Inputs = some_email.getElementsByTagName("input"); 
    for (var i = 0; i < in_Inputs.length; i++) { 
     if (in_Inputs[i].className == "email_class") 
     { 
      if (bad_email_check ...) 
      { 
       ret_val = true; 
       alert('enter valid email'); 
      } 
     } 
    } 
    return ret_val; 
} 

function addLoadEvent(some_function) 
{ 
    var oldonload = window.onload; 
    if (typeof window.onload != 'function') 
    { 
     window.onload = some_function; 
    } 
    else 
    { 
     window.onload = function() 
     { 
      oldonload(); 
      some_function(); 
     } 
    } 
} 

addLoadEvent(check_email); 

if (email_address_correctly_entered){ 
    do_something(); 
} 
+0

問題不清楚。添加更多細節。 – Manwal

+0

我正在尋找一種機制,只有在電子郵件字段驗證成功後纔會調用do_something()方法*,然後通過按「SUBMIT」按鈕觸發該機制。所以,這應該是任務的順序:表單加載,電子郵件字段被填充並且「SUBMIT」按鈕被推送,如果電子郵件字段值正確,請調用do_something()。 – user4856216

回答

0

試試這個:

in_Inputs = some_email.getElementsByTagName("input"); 

var model = { 
    index: 0, 
    ret_val: false 
} 

function check_this_email(in_Inputs, model) { 

    if(model.index > in_Inputs.length){ 
     return model.ret_val; 
    } 

    bad_email_check(in_Inputs, model, check_this_email); 
} 


function bad_email_check(in_Inputs, index, callback){ 
     //check  email in_Inputs[model.index] 
     //if valid email model.ret_val = true 
     model.index++ 
     if(model.ret_val){ 
      do_something(callback, in_Inputs, model); 
     } 
     else{ 
      callback(in_Inputs, model); 
     }   
} 

function do_something(callback, in_Inputs, model){ 
    //do something 

    callback(in_Inputs, model); 
} 

工作示例上的jsfiddle:https://jsfiddle.net/d81wmm61/

+0

謝謝,但正如我在我上面的評論中提到的,任務的順序應該是:表單加載,電子郵件字段被填充,並且「提交」按鈕被推送,如果電子郵件字段值正確,請調用do_something()。 – user4856216