将 Element id 设置为变量 - JavaScript / HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26338605/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:45:13  来源:igfitidea点击:

Set an Element id to a variable - JavaScript / HTML

javascripthtmlvar

提问by jdnoon

I was wondering if it was possible to add an id to a variable in JavaScript.

我想知道是否可以在 JavaScript 中向变量添加 id。

Like This...

像这样...

JavaScript:

JavaScript:

var name = "#userid";

HTML:

HTML:

<input type="text" id="userid" />

... So I want to set a variable to the input in the HTML. I have tried using

...所以我想为 HTML 中的输入设置一个变量。我试过使用

getElementById()

I'd like it so when a "userid" is entered into the input, I would like to set that to a variable in JS.

我喜欢它,所以当“userid”输入到输入中时,我想将它设置为 JS 中的一个变量。

Much Appreciated...

非常感激...

Thank You, James Noon

谢谢你,詹姆斯中午

回答by freefaller

This will update a global variable called name, when the value in the textbox is changed (but only once the user has left the control, by clicking or tabbing out)...

这将更新一个名为 的全局变量name,当文本框中的值发生更改时(但只有在用户离开控件时,通过单击或跳出)...

<input type="text" id="userid" onchange="name=this.value;" />

If you want to update the global variable at some other time (a different event) then you want this script...

如果您想在其他时间(不同的事件)更新全局变量,那么您需要此脚本...

var name = document.getElementById("userid").value;

回答by Nishad K Ahamed

<input type="text" onChange="setValue(this.value)">


function setValue(value){

var textVal=value;//here u will get the entered text

}