日期:2014-05-16  浏览次数:20388 次

关于事件绑定分离的问题
新手啊
html文件
HTML code
<!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>

我是这样绑定的,行吗?
js.js

JScript code
document.getElementById('hello').onclick = function(){
    alert("你好");
    };


这样绑定有什么不好吗?
我想把这个事件写成函数绑定,要怎么做呢?


------解决方案--------------------
我对jquery用的比较多 你可以试下 先导入jquery.js 然后只要用命令
$(function(){
 $("#hello").click(function(){
alert("1")
}) 
})
------解决方案--------------------
HTML code

<!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事件处理函数中。
JScript code
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的加载。
------解决方案--------------------
探讨

引用:

<script src="js.js" type="text/javascript"></script> 放在最底下不见得是坏事哦


为什么?不是说不符合W3C标准吗?

------解决方案--------------------
HTML code
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("你好");
    })

------解决方案--------------------
探讨

引用:

引用:

引用:

<script src="js.js" type="text/javascript"></script> 放在最底下不见得是坏事哦