如何获取调用 javascript 函数的文本框的 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11224271/
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
How do I get the id of a textbox that is invoking a javascript function?
提问by user1485327
What I want is to get the id (i.e myHeader, myHeader2, etc.)
我想要的是获取 id(即 myHeader、myHeader2 等)
This is what I'm trying now,
这就是我现在正在尝试的
HTML:
HTML:
<input type="text" id="myHeader" onblur="getValue(this)" />
<input type="text" id="myHeader2" onblur="getValue(this)" />
<input type="text" id="myHeader3" onblur="getValue(this)" />
<input type="text" id="myHeader4" onblur="getValue(this)" />
Javascript:
Javascript:
function getValue(obj){
var someVar = document.getElementById(obj).value;
}
But I'm not getting anything, the event is not firing as well, how do I do this?
但是我什么也没得到,事件也没有触发,我该怎么做?
回答by antyrat
Your obj
object already have id
and value
property:
您的obj
对象已经拥有id
和value
属性:
function getValue(obj){
alert('id - ' + obj.id);
alert('value - ' + obj.value);
}
Note that when you pass this
context to your function, you pass your DOM element. Not id. And you can operate with it already as with DOM element. No need for document.getElementById
.
请注意,当您将this
上下文传递给函数时,您传递的是 DOM 元素。不是身。您可以像使用 DOM 元素一样使用它。不需要document.getElementById
。
回答by Vinoth Kumar
function value(object)
{
alert('id= ' + object.id);
}
回答by Some Java Guy
As I see it, you might be firing the function when user loses focus on that input field.
在我看来,当用户失去对该输入字段的关注时,您可能会触发该功能。
Unless you are doing obj.value.toUpperCase();
why do you want to fire the same function on each input field?
除非您正在做,否则obj.value.toUpperCase();
为什么要在每个输入字段上触发相同的功能?
Anyways as @antyrat said this
would give you the DOM element and you can pick value
from it.
无论如何,正如@antyrat 所说的this
那样会给你 DOM 元素,你可以从中选择value
。
function getValue(obj){
obj.value=obj.value.toUpperCase();
}
this would make all for of your input fields to upper case
as user keeps moving ahead.
upper case
随着用户不断前进,这将使您的所有输入字段成为可能。
回答by Prince Antony G
<script type="text/javascript">
function getValue(obj) {
var id = obj.id;
var value = obj.value;
}
</script>
回答by Phoenix
Also you can get the textbox id
你也可以得到文本框ID
<input type="text" id="myHeader" onblur="getValue(this.id)" /> <!-- instead of getValue(this) -->
<script type="text/javascript">
function getValue(id) {
alert(id); // Display the id of the textbox
}
</script>
Hope it will help you.
希望它会帮助你。