2013-06-25 118 views
0

所以我已經有了一些幫助,我幾乎在那裏,但我想知道如果它可能有一個場焦點,當我打進入假設我在特定領域。當按下輸入按鈕時對焦一個字段

這是我的代碼:http://jsfiddle.net/spadez/xT5X5/2/

爲了得到它把重點放在「當前」場時,我打在「接受」字段中輸入。如果您先添加一些內容,然後點擊添加的字段並點擊回車,就可以看到這一點。我想這個代碼,而無需太多的運氣:

$(".accepted").keyup(function(e) { 
    if (e.which == 13) { 
     $(".current").focus(); 
    } 
}); 

另外,我想知道是否有添加這些「輸入」命令到我的代碼更好的方法,因爲它看起來有可能是一個更好的辦法。

+0

您顯示的代碼有什麼問題? –

+0

它不起作用:( – Jimmy

+0

.current是一個類名,並且該類有多個字段,如果你想關注一個特定的字段,你可能會給該字段一個唯一的ID並通過id $('# ())。焦點() – daghan

回答

2

更換

$(".accepted").keyup(function(e) { 
    if (e.which == 13) { 
     $(".current").focus(); 
    } 
}); 

有:

$(document).on("keyup",".accepted",function(e) { 
    if (e.which == 13) { 
     $(this).closest('.copies').next().find(".current").focus(); 
    } 
}); 

檢查demo

+0

這將始終聚焦相同.current元素 –

+0

是的,謝謝你的作品,但它選擇了錯誤的元素關注於http://jsfiddle.net/spadez/xT5X5/5/ – Jimmy

+0

@roasted:實際上,他需要類似$(this).parent()。find(「。current」)。focus(); –

1

問題是您在頁面加載時設置了keyup事件,然後動態創建了文本框 - 結果是文本框沒有綁定到任何事件。

所以,你有2個選項添加onClick =「」到文本框的或移動的創建像下面的綁定。

http://jsfiddle.net/xT5X5/4/

  $(html).appendTo(container); 

      $(".accepted").keyup(function(e) { 
       if (e.which == 13) { 
        $(".current").focus(); 
        return false; 
       } 
      }); 
+0

或更好,請使用委託 –

1

您需要更改代碼的一部分,你Ç opied這樣:

$('.form').on('keyup', '.accepted', function(e) { 
    if (e.which == 13) { 
     var line = $(this).parent(); // this targets '.line' 
     //this targets line's "container", which is '.copy', then find all the .current's in the next node (.line) 
     var current = $(line).parent().next().find('.current'); 

     //as var current returns a list with all the .current's found, even if there's only one, it returns an array of elements in case there were more, so we select the first one from the array 
     current = $(current)[0]; 
     $(current).focus(); 
    } 
}); 

說明: 作爲.accepted是文件裝載後創建一個類,它不存在,當你綁定KEYUP功能

您需要使用上()來代替,目標'.accepted',

我已經分解了如何找到'.current'你想讓你理解它,但你可以通過幾種方式實際達到它。我使用了一個我認爲會更容易理解的鏈接,下面是鏈接到工作小提琴:http://jsfiddle.net/QaHB3/1/

相關問題