正如标题所说,当我尝试获取元素的 id 属性时,我总是得到“undefined”,基本上我想做的是在值为“other”时用输入框替换元素。
代码如下:
function showHideOther(obj) {
var sel = obj.options[obj.selectedIndex].value;
var ID = $(this).attr("id");
alert(ID);
if (sel == 'other') {
$(this).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(this).css({
'display': 'none'
});
}
}
HTML:
<span class='left'><label for='race'>Race: </label></span>
<span class='right'><select name='race' id='race' onchange='showHideOther(this);'>
<option>Select one</option>
<option>one</option>
<option>two</option>
<option>three</option>
<option value="other">Other</option>
</select>
</span>
这可能是我没有注意到的小事,我做错了什么?
最佳答案
改变
var ID = $(this).attr("id");
到
var ID = $(obj).attr("id");
您也可以将其更改为使用 jQuery 事件处理程序:
$('#race').change(function() {
var select = $(this);
var id = select.attr('id');
if(select.val() == 'other') {
select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
} else {
select.hide();
}
});
关于javascript - $(this).attr ("id") 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3341342/