为什么我的 JavaScript 变量不能跨函数持久化?
我的 HTML 页面中有以下 JavaScript 引用页面上的 HTML 表单:
<script type="text/javascript">
<!--
var myForm = document.myForm;
function validateForm() {
if (myForm.myInput == "")
alert("Please input some text.");
return false;
}
myForm.submit();
}
function showFormInput() {
myForm.reset();
document.getElementById('myInput').style.display = 'inline';
}
//-->
</script>
...
<form name="myForm" id="myForm" action="..." method="post">
<input id="myInput" name="myInput" type="text" value="" style="display:none;" />
</form>
尝试访问变量 myForm
时,两个函数都会抛出异常,表示“myForm 为 null 或不是对象”。为什么会出现这种情况?
更新:我认为我从中收集到的一件事是全局变量通常应该用于字符串文字 - 而不是 DOM 中的元素。我将继续这一点,并谨慎使用元素变量,并且仅在 DOM 加载之后才使用。
I have the following JavaScript in my HTML page referencing an HTML form on the page:
<script type="text/javascript">
<!--
var myForm = document.myForm;
function validateForm() {
if (myForm.myInput == "")
alert("Please input some text.");
return false;
}
myForm.submit();
}
function showFormInput() {
myForm.reset();
document.getElementById('myInput').style.display = 'inline';
}
//-->
</script>
...
<form name="myForm" id="myForm" action="..." method="post">
<input id="myInput" name="myInput" type="text" value="" style="display:none;" />
</form>
Both functions are throwing an exception when trying to access the variable myForm
, saying that "myForm is null or not an object". Why is this occurring?
UPDATE: One thing I think I'm gathering from this is that global variables should generally be used for string literals - not elements in the DOM. I"m going to go forward with this, and use element variables sparingly, and only after the DOM has been loaded.
发布评论
评论(3)
您使用什么浏览器?
一般来说,您永远不应该使用
document.*
访问。这是 MS-IE 约定。相反,请使用如前所述,要么将脚本块放在页面底部,要么使用 的
onload
事件。标签,像这样What browser are you using?
IN general you should never use
document.*
access. This is an MS-IE convention. Instead, useAs outis noted, either put your script block at the bottom of your page, or use the
onload
event of <body> tag, like this如果示例代表页面,则在评估脚本时表单“myForm”不存在。除了使用
document.getElementById
(或document.forms.formName
)之外,您还需要延迟设置var myForm< /code> 直到处理完表单元素之后,或者更好,将表单作为函数的参数而不是使用全局变量。
If the sample is representative of the page, the the form "myForm" doesn't exist when the script is evaluated. In addition to using
document.getElementById
(ordocument.forms.formName
), you'll need to delay settingvar myForm
until after the form element is processed or, better yet, pass the form as an argument to the functions rather than using a global variable.您的问题出在
document.myForm
中。您可能想要使用:更新:其他答案还发现了另外几个问题:
正如 bobobobo 在另一个答案中指出的,您应该使用
document.getElementById()
来myForm.myInput
也是如此。此外outis还遇到了另一个问题因为您应该将块放置在 HTML 文档末尾附近,就在结束