2013-10-03 87 views
2

我已經在web應用以下情況我的工作:放置焦點上輸入框在IE

我有與一組索引字段值的,用戶將信息輸入表格並提交表單到服務器。字段驗證發生在服務器上。如果發現任何字段無效,表單會重新顯示,我希望輸入焦點自動轉到第一個無效字段。我有代碼來實現它,但問題是焦點並沒有放在IE 10的領域(但它被放置在Firefox中)。

placefocusonfirstinvalidindexfield(); 

    // After an attempt to upload has failed due to one or more invalid fields, then place the input focus automatically on the first 
    // invalid field: 
    function placefocusonfirstinvalidindexfield() { 
    var hasattemptedupload = '@Model.HasAttemptedUpLoadNumeric'; 
    if (hasattemptedupload == 1) { 
     var indexfirstinvalidfield = '@Model.GetIndexOfFirstInvalidField()'; 
     // focusIndexField(indexfirstinvalidfield); 
     setTimeout(focusIndexField(indexfirstinvalidfield), 100); 
    } 
    } 

    function focusIndexField(fieldindex) { 
    var control = document.getElementById("field" + fieldindex); 
    control.focus(); 
    } 

在上面的代碼中,我已確認正在引用正確的字段。一切似乎都應該如此,除了在過程結束時,IE10並未將重點放在引用的字段上。爲什麼不,我必須做些什麼才能做到這一點?

回答

1

只是試圖在控制檯中測試IE。當測試重點放在此頁面上的「發佈答案」文本區域時,以下代碼正常工作。

setTimeout(function() { document.getElementById("wmd-input").focus() }, 5000);

也許有別的東西在你的代碼的焦點干擾?您是否嘗試過延長超時值以查看它是否與此有關?

+0

我試過把它延長到5秒,它仍然沒有把焦點放在IE10的字段上。 –

0

您正試圖在這行左右裝載DOM嗎?

setTimeout(focusIndexField(indexfirstinvalidfield), 100); 

該行無法按預期工作。 focusIndexField立即執行,並且函數的響應由setTimeout函數延遲100 ms。

這將是你期望的工作:

setTimeout(function() {focusIndexField(indexfirstinvalidfield)}, 100); 

然而,這不是一個很好的解決方案。代碼應該在文檔準備就緒時執行。

+0

您對setTimeout函數是正確的,但如您所說的那樣更改它並不會使該字段在IE 10中獲得焦點。在文檔準備就緒時(無論是否超時),都不會執行代碼。 IE10不尊重focus()方法。 –

+0

也許你應該嘗試在JS小提琴中重現問題,所以我們也得到了html代碼? – 2013-10-05 08:17:56