我正在寻找一种从jquery访问选择标签的id属性的方法。
假设我在表单上有一个选择标签:表单.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
感谢您的任何帮助
如果您在select
的事件中尝试change
它将如下所示:
$('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');
可以在指向option
元素的$(this).attr("id")
中this
。
试试这个,
var id;
if(this.tagName === 'option'){
id = $(this).parent().attr('id');
}
else{
id = $(this).attr("id");
}
尝试:
$(this)[0].id
或
this.id
你可以
试试这个!
<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);
});
});