为什么
我有一个动态隐藏文本输入字段的表单,具体取决于加载时选项字段的初始选择。经过一番尝试和错误后,我意识到必须将 标记放置在
元素下方才能使此功能正常工作
<html>
....
<body>
....
<form>
<select name=choice>
<option value=0 selected>Default</option>
<option value=1>Others</option>
</select>
<input type=text name=others></input>
</form>
....
<script type='text/javascript'>
function init()
{
var A = document.forms[0].choice;
var B = document.forms[0].others;
if(A.options[A.selectedIndex].value == 0) B.style.display = 'none';
}
window.onload = init();
</script>
....
</body>
</html>
: window.onload
是一个全局事件,在页面所有资源(包括 DOM、图像、框架等)加载后触发。那么,为什么还需要将 标签放置在
元素下方呢?
I have a form that hides a text input field dynamically, depending on the initial choice of an option field upon loading. After some trial and error, I realise that the <script>
tag has to be placed below the <form>
elements in order for this functionality to work:
<html>
....
<body>
....
<form>
<select name=choice>
<option value=0 selected>Default</option>
<option value=1>Others</option>
</select>
<input type=text name=others></input>
</form>
....
<script type='text/javascript'>
function init()
{
var A = document.forms[0].choice;
var B = document.forms[0].others;
if(A.options[A.selectedIndex].value == 0) B.style.display = 'none';
}
window.onload = init();
</script>
....
</body>
</html>
The event window.onload
is a global event that is triggered after all resources of the page including DOM, images, frames, etc have loaded. Then, why is it still necessary for the <script>
tag to be placed below the <form>
elements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您执行
init 函数
而不是将指针分配给该函数...更改:
到:
Because your executing the
init function
instead assigning the pointer to the function...Change:
To:
这是因为您的代码中存在拼写错误:
这实际上是立即调用
init
函数(然后将window.onload
设置为 undefined)。尝试:It's because of a typo in your code:
This is actually calling the
init
function immediately (and then settingwindow.onload
to undefined). Try:JavaScript 和 HTML 工作正常。但我发现你的代码有些不理解。
此行表示立即执行 init 函数并将函数结果设置为 onload 事件。这就是为什么当您将其放置在表单元素下时它会起作用的原因。
JavaScript and HTML works correctly. But I see some miss understand on your code.
This line means use execute init function immediately and set function result as onload event. That is the reason why it works when you place it under form element.