2013-09-23 19 views
0

我有一些具有相同類名的元素。但是我想給id一個由用戶點擊的元素。如何爲jquery中的元素添加id

$('body').click(function(event) { 
    $(document).on('click', '.l1', function(){ 
     $('.l1').removeAttr('id'); 
     $('.l1').attr('id','selected'); 
    }); 
    $(document).on('hover', '.l1', function(){ 
    alert($(this).attr('id')); 
    }); 
}); 

小提琴:

http://jsfiddle.net/JamesPJ/h722g/141/

+1

使用'$(本)的元素',而不是'$(」 .li')' – schnill

回答

4

$('.l1')將始終選擇該類的所有元素,不顧事實,你是一個特定元素的單擊事件中。

你想用$(this)

Demo

+0

謝謝... It Worked .. – james

1

使用$(this)這樣它會指向你點擊

$(document).on('click', '.l1', function(){ 
     $('.l1').removeAttr('id'); 
     $(this).attr('id','selected'); 
    }); 
+0

謝謝...它工作.. – james

+0

不客氣。 –