2012-06-25 15 views
0

可能重複:
Getting the ID of the element that fired an event using JQuery在jQuery中,我如何檢索給定類的ID?

舉一個例子,假設我後來有

<p id="name" class="editable"... 

在JavaScript中我有

$("#editable").focusout(function(e){... 

如何檢索剛剛失去焦點的元素的ID?

+1

如果你的選擇是'.editable'? – alex

+4

'this.id' ...... –

+0

@Esailija:好找!我將它添加到標記wiki中,我們應該在那裏建立一個適當的FAQ(我認爲這是其中的一個)。 –

回答

3

你有錯選擇在jQuery中,必須是:

$(".editable") 

要提醒元素失去焦點,您需要使用this上下文選擇內回調:

$(".editable").focusout(function() { 
    alert($(this).attr('id')); 
}); 
+0

['.focusout()'](http://api.jquery.com/focusout/) – nnnnnn

+0

@nnnnnn好吧,我已經更新了我的答案。 – antyrat

1
$(".editable").focusout(function(e){ 
    var id = $(this).attr('id'); 
}); 

或者,如果.editable元素只是一個包裝和有趣的元素(input)是它的一個孩子,然後:

$(".editable").focusout(function(e){ 
    var id = $(e.target).attr('id'); 
});​ 

演示:http://jsfiddle.net/sveinatle/MWvAV/1/

相關問題