关于事件绑定分离的问题
新手啊
html文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script src="js.js" type="text/javascript"></script><title>无标题文档</title></head><body><a id="hello">学习</a></body></html>
document.getElementById('hello').onclick = function(){ alert("你好"); };<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gbk" /><title>无标题文档</title></head><body><a id="hello">学习</a><script> function $(el){ return typeof el == 'string' ? document.getElementById(el) : el; } $('hello').onclick = function(){ alert( this.innerHTML ) }</script></body></html>
[解决办法]
没什么区别,但要注意代码的顺序,像你写的代码就无法绑定,因为js代码放在a标签前面,这时a元素还没有加载到DOM树中,所以无法通过getElementById('hello')获取这个a元素对象。解决方法是,要么把js代码写到目标元素后面,要么写到window.onload事件处理函数中。
function demo() { alert('test'); }window.onload = function() { document.getElementById('hello').onclick = demo;}
[解决办法]
<script src="js.js" type="text/javascript"></script> 放在最底下不见得是坏事哦
[解决办法]
是的,可以放在页面底部,
<script src="js.js" type="text/javascript"></script>
这样的外联放页头 会阻塞页面的加载,影响dom的加载。
[解决办法]
var addEvent = function(l, i, I) { if (l.attachEvent) { l.attachEvent("on" + i, I) } else { l.addEventListener(i, I, false) }}var delEvent = function(l, i, I) { if (l.detachEvent) { l.detachEvent("on" + i, I) } else { l.removeEventListener(i, I, false) }}var h = document.getElementById('hello');addEvent(h,'click',function(){ alert("你好"); })
[解决办法]