简体   繁体   English

Javascript document.getElementById

[英]Javascript document.getElementById

Im not sure why this is not working, can someone please tell me why? 我不确定为什么这行不通,有人可以告诉我为什么吗?

var red = [0, 100, 63];
var orange = [40, 100, 60];
var green = [75, 100, 40];
var blue = [196, 77, 55];
var purple = [280, 50, 60];

var myName = document.getElementById('mytext');
letterColors = [ red, orange, green, blue, purple ]
if(10 >  3) {
bubbleShape = "circle";
}

else {
    bubbleShape = "square";
}
drawName(myName, letterColors);
bounceBubbles()

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="alphabet.js"></script>
  </head>
  <body>
    <canvas id="myCanvas"></canvas>
    <script type="text/javascript" src="bubbles.js"></script>
    <script type="text/javascript" src="main.js"></script>
<head>
  Name: <input type="text" name="mytext"><br>
</form>
</head>
<body>
</body>
</html>

I am trying to get the variable "myname" to be what the user types into the text box. 我正在尝试获取变量“ myname”作为用户在文本框中键入的内容。

You are getting the reference to the element, but then you need to use the value property to the value from the element: 您正在获得对该元素的引用,但随后需要将value属性用于该元素的值:

var myName = document.getElementById('mytext').value;

You need to set the id of the element to access it using the getElementById method: 您需要使用getElementById方法设置元素的ID才能访问它:

<input type="text" name="mytext" id="mytext">

Also, it's not clear where the Javascript code is executed in the code, but if the code is the entire content of the alphabet.js , bubble.js or main.js file, then you are running the code before the content of the body has been parsed. 此外,它在JavaScript代码中的代码执行尚不明确,但如果代码是的全部内容alphabet.jsbubble.jsmain.js文件,那么你身体的内容之前运行的代码已解析。 To run the code after the content is loaded, use the load event: 要在加载内容之后运行代码,请使用load事件:

window.onload = function(){

  // code that uses the content goes in here

};

将ID属性设置为您的输入标签

<input type="text" id="mytext" name="mytext">

Change 更改

<input type="text" name="mytext">

To

 <input type="text" name="mytext" id="mytext">

Then use 然后使用

var myName = document.getElementById('mytext').value;

Like @Guffaa suggested. 就像@Guffaa建议的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM