2014-01-20 46 views
0

我試着在驗證失敗時專注於相同的元素。這裏是我的HTML代碼:Javascript - 在警報消息後設置焦點

<input id="potatoes" name="potatoes" value="" type="text" class="tooltip" onblur="Validate('potatoes')" autocomplete='off'>

,這裏是我的javascript代碼:

function Validate(id) { 
var errors = { 
    potatoes : 'enter potatoes', 
    hamburgers : 'enter' 
}; 
if (document.getElementById(id).value === '') { 
    if (id in errors) { 
     alert(errors[id]); 
     //setTimeout(function(){document.getElementById(id).focus();}, 1); 
    } 
} 

}

我試着用.focus()方法來設置焦點,但它不工作。我讀過它可能取決於HTML中的「onblur」,當我調用我的函數Validate()時,所以我試圖改變它,但到現在爲止沒有任何工作。

+1

的可能重複【如何將焦點()警報後() ?](http://stackoverflow.com/questions/7234190/how-to-give-focus-after-an-alert) – pasine

回答

1

這裏有個問題。此代碼正在循環中。當「焦點」被觸發時,函數Validate再次被調用,顯示另一個警報對話框。

這是一個工作代碼

HTML

<input id="potatoes" name="potatoes" value="" type="text" class="tooltip" onblur="Validate(this)" autocomplete='off'>

的Javascript

var validating = false; //<-- IMPORTANT 
function Validate(element) { 
var id = element.id; 

var errors = { 
    potatoes : 'enter potatoes', 
    hamburgers : 'enter' 
}; 
if (document.getElementById(id).value === '') { 
    if (id in errors) { 
      if(validating == false) { 
        validating = true 
      alert(errors[id]); 
      setTimeout(function(){ 
       document.getElementById(id).focus(); 
       validating = false; 
      }, 1); 
      } 
    } 
} 
} 

在我傳遞的HTML,這樣做我經過的克元素和驗證功能,您可以訪問該ID只調用

var id = element.id; 

對於焦點問題(由一個循環的問題),你可以看到我使用的是驗證可變知道什麼時候正在驗證什麼時候沒有。這讓Validate函數避免進入循環。 所以:

1)定義驗證 VAR 的驗證功能,並將其設置爲false。

2)火重點警報只有驗證是假的,之後將其設置爲真正

2

javascript函數alert(string)是同步的。當用戶對提醒的消息作出反應時,腳本暫停。沒有必要做一些特別的事情。以下代碼片段應該可以工作:

alert(errors[id]); 
document.getElementById(id).focus(); 

元素在用戶提交提醒消息後直接獲得焦點。

+0

'警報(字符串)'不是異步它是同步的,所以腳本一直等到警報對話框被關閉保持 – semirturgay

+0

只是拼錯了...謝謝 – WoIIe