2014-11-16 35 views
0

我試圖讓下一個輸入字段的ID,當用戶退出輸入字段:jQuery的nextall首先獲得ID

$("input").blur(function(){ 
var theid = $(this).attr('id'); 
var thefield = $(this).nextAll('input').first().attr('id'); 
alert(thefield); 
}); 

目前,它返回undefined。 的HTML代碼是:

<table><tr> 
<td>Number</td><td>Name</td> 
<tr><td>1 <input type='text' name='deltagernummer[]' value='' size='6' id='r0' tabindex='1' /></td> 
<td><input type='text' name='deltagernavn[]' value='' id='rr0' tabindex='-1' /></td></tr> 
<tr><td>2 <input type='text' name='deltagernummer[]' value='' size='6' id='r1' tabindex='2' /></td> 
<td><input type='text' name='deltagernavn[]' value='' id='rr1' tabindex='-1' /></td></tr> 
</table> 

什麼問題?

回答

3

Nextall()通過兄弟姐妹,您的輸入沒有兄弟姐妹。

$("input").blur(function(){ 
    var theid = $(this).attr('id'); 
    var thefield = $(this).closest('tr').next().find('input').attr('id'); 
    alert(thefield); 
}); 

http://jsfiddle.net/xq6snuLs/

+0

只要下一個''確實有一個輸入,這個工程。如果沒有,這會失敗。只是一個建議,因爲OP從未提及過這種情況。 :) – Joseph

6

.nextAll()掃描兄弟姐妹。雖然你的<input> s在同一水平,他們不是兄弟姐妹。以「可視化」,這裏的僞HTML:

孩子和孩子的兄弟姐妹:

<parent> 
    <child> 
    <childs-sibling> 
</parent> 

您的情況:

<parent> 
    <descendant> 
    <input> 
    </descendant> 
    <descendant-sibling> 
    <totally-unrelated-to-input> 
    </descendant-sibling> 
</parent> 

你可以做的是爬上<tr>水平,成功行,得到所有的輸入,得到第一個,然後得到的ID。

var id = $(this) 
    .closest('tr')   // Get to the row level 
    .nextAll('tr')   // Get all succeeding rows 
    .find('td > input')  // Find the inputs. You may adjust the selector. 
    .eq(0)     // Get the first input 
    .attr('id');    // Get its id, if any