Basic jquery question. I have an option element as below.
基本的jquery的问题。我有一个选项元素如下所示。
<option class='select_continent' value='7'>Antarctica</option>
jquery
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.
这就产生了一个错误。attr不是函数,所以我没有正确地使用“this”。
How can i get it to alert 7?
我怎么才能让它发出警报?
4 个解决方案
#1
59
You need to do:
你需要做的:
alert($(this).attr('value'));
#2
42
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岗位上,情况并非如此。
Note that if you're not going to do any further jQuery operations on the ID attribute (on that line of code) -- that is, if you are just storing the returned text into a variable, then plain js is faster:
注意,如果您不打算对ID属性(在代码行上)进行任何进一步的jQuery操作——也就是说,如果您只是将返回的文本存储到一个变量中,那么普通的js会更快:
alert( this.id );
#3
2
You can also try this way
你也可以这样尝试
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
jquery
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
祝你好运! ! ! !
#4
1
$('.select_continent').click(function () {
alert($(this).attr('value'));
});
#1
59
You need to do:
你需要做的:
alert($(this).attr('value'));
#2
42
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岗位上,情况并非如此。
Note that if you're not going to do any further jQuery operations on the ID attribute (on that line of code) -- that is, if you are just storing the returned text into a variable, then plain js is faster:
注意,如果您不打算对ID属性(在代码行上)进行任何进一步的jQuery操作——也就是说,如果您只是将返回的文本存储到一个变量中,那么普通的js会更快:
alert( this.id );
#3
2
You can also try this way
你也可以这样尝试
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
jquery
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
祝你好运! ! ! !
#4
1
$('.select_continent').click(function () {
alert($(this).attr('value'));
});