2012-04-26 130 views
-1

我可以这样做吗?获取名称或类别的按钮元素ID

 var gender = $('.ImdbAddArtist').click(function() { 
    alert(this.id); 
}); 

我使用下面的代码,但它有点奇怪。

我可以从他们的名字有按钮的ID?

+3

你试过了吗?它应该工作正常。 – 2012-04-26 15:05:52

+0

是的。你可以用$(“[name = YourElementName]”)查询。 – 2012-04-26 15:07:55

+0

你甚至试过这个吗?它工作正常。 – 2012-04-26 15:13:49

回答

2

是的。您的代码将正常工作:

//Bind click event handler to all elements with class of 'ImdbAddArtist' 
var gender = $('.ImdbAddArtist').click(function() { 
    /* When clicked, alert the value of the 'id' property of 'this'. 
    'this' refers to the element that was clicked. */ 
    alert(this.id); 
}); 

只要点击的元素有一个id属性,你会得到显示该值的警报。如果它没有id属性,则会收到空白警报。

这里是working example

1

$('.ImdbAddArtist')。这选择 一个元素 多个元素。

一旦选定了这些元素,您就可以随心所欲地做任何事情。

如果一个元素有一个id,你可以得到这个id,这与它的选择无关。

+0

严格地说,它不选择一个或多个元素,因为它是一个类选择器。 – 2012-04-26 15:09:46

+0

@AnthonyGrist:真的,让我解决这个问题。 – 2012-04-26 15:10:44

+0

$('ImdbAddArtist')。attr(“id”);给我undefined:S – snnlankrdsm 2012-04-26 15:11:31

1

你的代码工作正常,但我想去.attr()方法来获取元素属性...

的元素alert($(this).attr("id"));

的ID类元素的alert($(this).attr("class"));

只使用.attr ()函数的jquery将得到元素的ID

+2

为什么加入额外的负担再次调用jQuery,然后调用一个jQuery方法,何时可以直接在元素上访问属性? – 2012-04-26 15:09:02

+1

@JamesAllardice因为更多的jQuery总是更好! – 2012-04-26 15:10:01

+0

哪个元素我没有定义 – snnlankrdsm 2012-04-26 15:10:10