jquery:如何获取id属性的值?

ste*_*tef 43 jquery

基本的jquery问题.我有一个选项元素如下.

<option class='select_continent' value='7'>Antarctica</option>  
Run Code Online (Sandbox Code Playgroud)

jQuery的

$(".select_continent").click(function () {
  alert(this.attr('value'));
});
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误,说this.attr不是一个函数,所以我没有正确使用"this".

我怎样才能让它提醒7?

dan*_*vis 73

你需要这样做:

alert($(this).attr('value'));
Run Code Online (Sandbox Code Playgroud)

  • 或者`$(this).val()` (22认同)

css*_*hus 52

要匹配此问题的标题,该id属性的值为:

var myId = $(this).attr('id');
alert( myId );
Run Code Online (Sandbox Code Playgroud)

但是,当然,元素必须已经定义了id元素,如:

<option id="opt7" class='select_continent' value='7'>Antarctica</option>
Run Code Online (Sandbox Code Playgroud)

在OP职位中,情况并非如此.


重要:

请注意,普通js更快(在这种情况下):

var myId = this.id
alert(  myId  );
Run Code Online (Sandbox Code Playgroud)

也就是说,如果您只是将返回的文本存储到变量中,如上例所示.这里不需要jQuery的精彩.


sal*_*med 5

你也可以试试这个方法

<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
Run Code Online (Sandbox Code Playgroud)

查询

$('.select_continent').click(function () {
alert($(this).data('value'));
});
Run Code Online (Sandbox Code Playgroud)

祝你好运 !!!!