2013-04-07 66 views
1

检索一个元素的id我有一些元素具有相同的CSS类通过其CSS类

我想知道我怎么可以检索他们中的一个的ID;如第一个与该类

这是我当前的代码,但它不工作

$('.imageofarticle').mousemove(function(){ 
    var a = $(this).attr('id'); 
    var tableau = a.split(":"); 
    alert("get the first : "+$('.showmovingEdit').[0].attr('id')); 
    // $('.showmovingEdit')[tableau[1]].show(); 
}); 

回答

1

你有额外的dot,并呼吁ATTR上DOM对象,而不是直接访问id

变化

$('.showmovingEdit').[0].attr('id') 
        ^

$('.showmovingEdit')[0].id 

,或者使用get()

$('.showmovingEdit').get(0).id 

,或者使用eq()

$('.showmovingEdit').eq(0).attr("id"); 

编辑

每个jQuery对象也伪装成一个数组,这样我们就可以使用 阵列对其操作来获得在列表项改为:Reference

alert($('selector')[0]); //gives first element returned by selector. 
+0

谢谢你的工作 – simonTifo 2013-04-07 14:47:22

+0

不用客气@simonTifo – Adil 2013-04-07 14:51:57

+0

你能告诉我参考 – simonTifo 2013-04-07 14:54:25

3

您的代码语法是错误的,选择的第一个元素,你可以使用first方法:

// Return the first element in jQuery collection 
$('.showmovingEdit').first().attr('id'); 

为了选择其它元素,可以使用eq方法:

// Return an element based on it's index in jQuery collection 
$('.showmovingEdit').eq(index).attr('id'); 

注意,当[index]使用(正确),它返回没有attr方法的DOM元素的对象,你应该使用id属性,而不是:

// Select the first DOM element in the set and return it's ID property 
var id = $('.showmovingEdit')[0].id; 
1

只要使用此:

$('.showmovingEdit').attr('id') 

另外,指的是其他许多帖子:你不需要first()。如果不带参数调用attr()将自动获取第一个元素。