将元素id设置为一个变量JavaScript/HTML

Set an Element id to a variable - JavaScript / HTML

本文关键字:一个 变量 JavaScript HTML id 元素 设置      更新时间:2023-09-26

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

像这样。。。

JavaScript:

var name = "#userid";

HTML:

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

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

getElementById()

我希望在输入中输入"userid"时,将其设置为JS中的一个变量。

非常感谢。。。

谢谢你,James Noon

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

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

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

var name = document.getElementById("userid").value;
<input type="text" onChange="setValue(this.value)">

function setValue(value){
var textVal=value;//here u will get the entered text
}