2016-05-16 57 views
0

我試圖將焦點設置爲一個元素,然後立即將其設置回以前的焦點項目。這裏的HTML:jQuery專注於一個元素,然後另一個立即

<input id="em3" type="email" /> 
<p class="error" tabindex="0">Please fill out the email field</p> 

我已經試過這樣:

$(this).next('.error').focus(); 
$(this).prev('input').focus(); 

這:

$(this).next('.error').focus(); 
setTimeout(function(){ 
     $(this).prev('input').focus(); 
}, 2000); 

但無論是作品。焦點停留在「.error」元素上。

任何想法?

+1

運行代碼時,哪個元素是'this'?改變焦點到下一個元素不會改變'this'。所以,如果你從'input'開始並想回到它,它應該是'$(this).focus()'。 – Barmar

回答

0

的問題是:

這是因爲$(this)在setTimeout的處理程序是指 窗口,這大概是不一樣的價值由 $(this)處理程序外引用。所以,你需要指定您$(this)在 外部範圍

var ThisIt = $(this); 
ThisIt.next('.error').focus(); 
setTimeout(function(){ 
     ThisIt.focus(); 
}, 2000); 

演示

$('#em3').on('click',function(){ 
 
    var ThisIt = $(this); 
 
    ThisIt.next('.error').focus(); 
 
    setTimeout(function(){ 
 
     ThisIt.focus(); 
 
    }, 2000); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="em3" type="email" /> 
 
<p class="error" tabindex="0">Please fill out the email field</p>

注:1:點擊輸入查看動作.. 第2張:正如@Barmar在評論中所說..不需要使用prev()

+0

謝謝你們。當你在頁面上有一對輸入和錯誤時不起作用,但它會陷入循環。因此「下一個」。更多上下文: $('input,select,textarea')。blur(function(e) {012;}(this).val()){ $(this).next('。error' )的CSS( '顯示器', '內聯'); \t \t變種ThisIt = $(本); ThisIt.next()聚焦() '錯誤。'; 的setTimeout(函數(){ ThisIt.focus ();} ,2000); } \t \t 否則{ $(本)的.next()的CSS( '顯示器 ' '無')' 錯誤。'; \t \t $(本)。最接近( '禮')。接下來( '禮')。找到( '*')。重點( ); } }); – DeanH

相關問題