我有几个文本框,其中有下拉菜单。当用户点击下拉类的字段时,我想获取该字段的ID。这似乎应该是简单的,但我不能完全似乎看着办吧......通过元素类获取ID
我曾尝试:
$(".dropdown").click(function() {
alert(this.getElementById);
});
这只能返回undefined。
我有几个文本框,其中有下拉菜单。当用户点击下拉类的字段时,我想获取该字段的ID。这似乎应该是简单的,但我不能完全似乎看着办吧......通过元素类获取ID
我曾尝试:
$(".dropdown").click(function() {
alert(this.getElementById);
});
这只能返回undefined。
ID是对象的属性,所以只需使用下面的代码:
$(".dropdown").click(function() {
alert(this.id);
});
谢谢!我无法想象正确的语法! –
@BarryTormey作为参考,'getElementById'是'document'对象的一个方法:https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById。它用于通过它们的'id'属性/属性检索一个元素。你只是在寻找你已经拥有的元素对象的属性('this') – Ian
好的。谢谢!我会保留这些以备将来参考。欣赏它! –
您使用getElementById
不正确。这是一个函数,用于在页面上使用id作为过滤条件来获取dom元素。它不用于获取元素ID。
的getElementById
正确的用法是
var elem = document.getElementById('theid');
您只需使用
alert(this.id);
错误syntax.You已经写
$(".dropdown").click(function() {
alert(this.id);
});
var idStr = element.id; // Get the id.
element.id = idStr; // Set the id
使用this.id +1 – musicnothing
如果我深知,想要此:
$(".dropdown").click(function() {
alert($(this).attr('id'));
});
纠正我,如果我错了
它的简单,你可以通过我
$(".dropdown").click(function() {
var id = $('.dropdown').attr('id');
alert(id);
});
写下面的代码提醒元素的id
@roasted答案应该工作,只是混合你的jQuery和JavaScript在同一评估将无法正常工作。 :) – abc123