2012-08-29 48 views
1

我想做一個neseted事件。通過嵌套的事件中,我的意思是這樣:Javascript嵌套事件

HTML:

<input type="text" onFocus='validStartDate()' name="start_date" id="startDate" /> 

的Javascript:

function checkCorrectStart() 
{ 
    document.getElementById("startDate").className = "focus"; 
    document.getElementById("startDate").onChange = function(){ 
     validStartDate(); 
    }; 
} 

function validStartDate() 
{ 
    re = /^\d{4}\-\d{2}\-\d{2}$/; 
    var aux = document.getElementById("startDate").value; 
    var valid = false; 

    if (aux.match(re)) 
    { 
     document.getElementById("startDate").className = "correct"; 
     valid = true; 
    } 
    else 
    { 
     document.getElementById("startDate").className = "wrong"; 
    } 
    return valid; 
} 

的想法是,當用戶集中在輸入框中就會使一個黃色的影子周圍然後當用戶改變該輸入框的內容時,它將驗證該輸入框是否正確,如果正確則進行綠色陰影,如果不正確則進行紅色陰影。

任何想法或任何其他建議如何做到這一點,將不勝感激。

+0

而我想你的意思是把onCorrectStart()放在onFocus屬性中。對? – DerekIsBusy

回答

0

如果你不想使用jQuery(使用普通的JavaScript),那麼你可以試試這個

window.onload=function(){ 
    var el=document.getElementById("startDate"); 
    el.onfocus=function(){ 
     var currentClass=el.parentNode.className; 
     if(currentClass!='correct') el.parentNode.className = "wrong"; 
    } 
    el.onchange = validStartDate; 
    el.onkeyup = validStartDate; 
} 

function validStartDate() 
{ 
    var el=document.getElementById("startDate"); 
    var re = /^\d{4}\-\d{2}\-\d{2}$/; 
    var aux = el.value; 
    var valid = false; 

    if (aux.match(re)) 
    { 
     el.parentNode.className = "correct"; 
     valid = true; 
    } 
    else 
    { 
     el.parentNode.className = "wrong"; 
     valid = false; 
    } 
    return valid; 
} 

我不包括css這裏,它在演示可用,但你需要使用你的頁面。

DEMO