为什么不在body元素上使用javascript处理程序? [英] Why not use javascript handlers on the body element?

查看:112
本文介绍了为什么不在body元素上使用javascript处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为'如何在网页加载时自动将焦点设置为文本框?' Espo 建议使用

 < body onLoad =document.getElementById('< id>')。焦点();> 

Ben Scheirman 回复(没有进一步解释):

lockquote

任何javascript书都会告诉你不是
将处理程序放在body元素上
就像那样


为什么这会被认为是不好的做法?在Espos的回答中,说明了一个优先问题。这是唯一的原因,还是还有其他问题?兼容性问题?

解决方案使用 onLoad 变得越来越不常见,因为回调不能用这个方法堆叠,即新的 onload 定义覆盖旧的。

在像jQuery和它的 .load()这样的现代框架中,回调函数可以堆叠起来,在同一页面上使用不同的脚本,插件等。

另外,将代码与标记分开的做法被广泛认为是很好的做法,所以即使有人愿意想要使用 onload (如果你控制完整的环境并知道你在做什么,这是完全没问题的),你可以在脚本端附加 head 或者一个单独的javaScript文件:

  window.onload = function(){ document.getElementById ......} 


As an answer to the question of 'How do you automatically set the focus to a textbox when a web page loads?', Espo suggests using

<body onLoad="document.getElementById('<id>').focus();">

Ben Scheirman replies (without further explanation):

Any javascript book will tell you not to put handlers on the body element like that

Why would this be considered bad practice? In Espos answer, an 'override' problem is illustrated. Is this the only reason, or are there any other problems? Compatibility issues?

解决方案

Using onLoad is becoming less and less common because callbacks can't be stacked using this method, i.e. new onload definitions override the old ones.

In modern frameworks like jQuery and its .load(), callbacks can be stacked and there are no conflicts when using different scripts, plugins, etc. on the same page.

Also, it is widely regarded good practice to keep the markup separate from the code, so even if one would want to use onload (which is perfectly okay if you control the complete environment and know what you're doing) one would attach that event on the scripting side either in the head or a separate javaScript file:

window.onload = function() { document.getElementById...... }

这篇关于为什么不在body元素上使用javascript处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆