简体   繁体   English

document.getElementById 每次都返回 null 或 undefined

[英]document.getElementById is returning null or undefined everytime

Javascript code is Javascript代码是

function addConformationNo(){   

  var confirmationNo = document.getElementById("addedconfirmation").val();    

  alert(confirmationNo);

}

and I'm calling addConformationNo() function on click of a button我在单击按钮时调用addConformationNo()函数

When the addConformationNo() function is executed, the function call to document.getElementById returns null everytime.addConformationNo()函数执行时,对document.getElementById的函数调用每次都返回 null。 Why?为什么? Any clues?有什么线索吗?

Either:任何一个:

  1. You don't have an element of that id您没有该 ID 的元素
  2. You are calling the function before the element exists您在元素存在之前调用该函数
  3. You are misreading the error message您误读了错误消息

DOM elements do not have val methods associated with them, so you are likely to get a "Property is undefined or not a function" error, but that is complaining about val not the return value of getElementById . DOM 元素没有与它们关联的val方法,因此您可能会收到“属性未定义或不是函数”错误,但这是在抱怨val而不是getElementById的返回值。

Access the value property instead.改为访问value属性。

var confirmationNo = document.getElementById("addedconfirmation").value;    
var confirmationNo = document.getElementById("addedconfirmation").value;

will do.会做。

You can also inspect element by right clicking on the browser or you can check the javascript console in your browser.您还可以通过右键单击浏览器来检查元素,或者您可以检查浏览器中的 javascript 控制台。

<html>
<head>

<script type=text/javascript>
function addConformationNo(){

var confirmationNo = document.getElementById("addedconfirmation").value; 

alert(confirmationNo);

}
</script>

</head>
<body>
<input type = "text" name = "addedconfirmation" id = "addedconfirmation" />
<input type="submit" onclick="addConformationNo();">
</body>
</html>

If you are getting such a message for every element.如果您为每个元素都收到这样的消息。 Then you may have included the javascript file at the beginning of HTML on the top instead of the bottom.那么您可能在顶部而不是底部的 HTML 开头包含了 javascript 文件。

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

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