我試着在驗證失敗時專注於相同的元素。這裏是我的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()時,所以我試圖改變它,但到現在爲止沒有任何工作。
的可能重複【如何將焦點()警報後() ?](http://stackoverflow.com/questions/7234190/how-to-give-focus-after-an-alert) – pasine