0

我正在寻找一种从 jquery 访问 select 标记的 id 属性的方法。

说我在表单上有一个选择标签:form.php

<select id="testid">
<option value="1">1</option>
<option value="2">2</option>
</select>

从 jquery 我可以访问选项值作为$(this).attr("value"). 但是$(this).attr("id")变得不确定。

通过为选项标签提供一些 id 属性值,它可以工作。但是,有没有办法通过$(this)对象访问选择标签的 id

谢谢你的帮助

4

4 回答 4

2

如果您在change事件中尝试,select它将如下所示:

$('select').change(function() {

    // here 'this' point to select

   console.log( $(this)[0].id );

   //OR simply

   console.log(this.id);

})

$(this).attr('id')也应该工作。

如果你的$(this)option然后尝试

$('select').has(this).attr('id');

或者

$(this).parent('select').attr('id');
于 2012-06-06T04:59:25.587 回答
2

可能this$(this).attr("id")指向option元素。

试试这个,

var id;
if(this.tagName === 'option'){
    id = $(this).parent().attr('id');
}
else{
   id = $(this).attr("id");
}
于 2012-06-06T05:03:27.363 回答
1

尝试:

$(this)[0].id

或者

this.id
于 2012-06-06T05:16:18.980 回答
0

你可以试试这个!

<select id="testid">
<option class='option' value="1">1</option>
<option class='option' value="2">2</option>
</select>

$(document).ready(function(){

$("#testid").change(function(){
var option = [];

$("option.option:selected").each(function(i){// this will filter the selected id

option[i] = $(this).val();
});
alert(option);
});
});
于 2012-06-07T07:29:45.787 回答