从jquery访问select标记的id属性

时间:2012-06-06 04:55:15

标签: php jquery

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

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

<select id="testid">
<option value="1">1</option>
<option value="2">2</option>
</select>
来自jquery的

我可以将选项值作为$(this).attr("value")来访问。但是$(this).attr("id")未定义。

通过为option标签提供一些id属性值,它可以正常工作。但是,有没有办法通过$(this)对象

访问select标记的id

感谢您的帮助

4 个答案:

答案 0 :(得分: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');

OR

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

答案 1 :(得分:2)

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

试试这个,

var id;
if(this.tagName === 'option'){
    id = $(this).parent().attr('id');
}
else{
   id = $(this).attr("id");
}

答案 2 :(得分:1)

尝试:

$(this)[0].id

this.id

答案 3 :(得分: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);
});
});