使用 JavaScript 获取输入字段的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30398718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get Id of input field using JavaScript
提问by Toxic
I have input in grid, which each unique ID, output as following;
我在网格中输入,每个唯一的 ID,输出如下;
<a href="#" class="SearchUser_Icon Hyperlink_Text" onclick="load_getUserListByGroupID()" id="2"></a>
I want to know what is equivalent to $(this).attr("ID") in javaScript
我想知道什么相当于javaScript中的$(this).attr("ID")
function load_getUserListByGroupID()
{
var selectedGroupID = document.getElementById('input');
alert(selectedGroupID);
}
回答by cн?dk
You can simply get it using .id
attribute like this:
你可以简单地使用这样的.id
属性来获取它:
this.id;
Or you can also use .getAttribute()
method:
或者你也可以使用.getAttribute()
方法:
this.getAttribute('id')
So your example should be, like thsi:
所以你的例子应该是这样的:
function load_getUserListByGroupID(element) {
alert(element.id);
}
<a href="#" class="SearchUser_Icon Hyperlink_Text" onclick="load_getUserListByGroupID(this)" id="2">aa</a>
回答by Satpal
Pass this
to onclick event handler. Then you can directly get its id.
传递this
给 onclick 事件处理程序。然后就可以直接得到它的id了。
Use
利用
<a href="#" class="SearchUser_Icon Hyperlink_Text" onclick="load_getUserListByGroupID(this)" id="2"></a>
Script
脚本
function load_getUserListByGroupID(elem){
alert(elem.id);
}
回答by jaeko44
Use a variable,
使用变量,
onClick="reply_click(this.id)"
function reply_click(clicked_id)
{
alert(clicked_id);
}
Add the OnClick function the element you'd like, this will also throw the ID value when processing to the function.
将 OnClick 函数添加到您想要的元素,这也会在处理函数时抛出 ID 值。
Hope this helps :)
希望这可以帮助 :)