jquery:如何获取 id 属性的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1618209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: how to get the value of id attribute?
提问by stef
Basic jquery question. I have an option element as below.
基本的jquery问题。我有一个选项元素,如下所示。
<option class='select_continent' value='7'>Antarctica</option>
jquery
查询
$(".select_continent").click(function () {
alert(this.attr('value'));
});
This gives an error saying this.attr is not a function so im not using "this" correctly.
这给出了一个错误,说明 this.attr 不是一个函数,所以我没有正确使用“this”。
How can i get it to alert 7?
我怎样才能让它警报7?
回答by danjarvis
You need to do:
你需要做:
alert($(this).attr('value'));
回答by cssyphus
To match the title of this question, the value of the id
attribute is:
为了匹配这个问题的标题,id
属性的值是:
var myId = $(this).attr('id');
alert( myId );
BUT, of course, the element must already have the id element defined, as:
但是,当然,元素必须已经定义了 id 元素,如下所示:
<option id="opt7" class='select_continent' value='7'>Antarctica</option>
In the OP post, this was not the case.
在 OP 帖子中,情况并非如此。
IMPORTANT:
重要的:
Note thatplain js is faster (in this case):
请注意,纯 js 更快(在这种情况下):
var myId = this.id
alert( myId );
That is, if you are just storing the returned text into a variable as in the above example. No need for jQuery's wonderfulness here.
也就是说,如果您只是将返回的文本存储到上面示例中的变量中。这里不需要jQuery的精彩。
回答by saleem ahmed
You can also try this way
你也可以试试这个方法
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
查询
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
祝你好运 !!!!
回答by billah77
$('.select_continent').click(function () {
alert($(this).attr('value'));
});