新手啊
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>
我是这样绑定的,行吗?
js.jsdocument.getElementById('hello').onclick = function(){
alert("你好");
};这样绑定有什么不好吗?
我想把这个事件写成函数绑定,要怎么做呢?
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>
我是这样绑定的,行吗?
js.jsdocument.getElementById('hello').onclick = function(){
alert("你好");
};这样绑定有什么不好吗?
我想把这个事件写成函数绑定,要怎么做呢?
$(function(){
$("#hello").click(function(){
alert("1")
})
})
<!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>操作dom,需要等dom加载完毕再做绑定等操作。
function demo() { alert('test'); }
window.onload = function() {
document.getElementById('hello').onclick = demo;
}
一下在寻找解决方法,也知道有个window.onload事件,但是不知道如何时绑定。
一般我都是把<script src="js.js" type="text/javascript"></script>放在最底下的。
但是感觉很不规范。现在懂了,呵呵。
这样的外联放页头 会阻塞页面的加载,影响dom的加载。
如果head里面放大量的js引用话,那么在页面加载的时候会出现一段空白页面,接着会出现页面内容
这一段空白页面的时间就在加载head里面的东西.为了用户体验,往往需要把这些js放在body底部,这样head里面内容少了,当页面加载的时候用户可以马上到页面的内容
不是说<script src="js.js" type="text/javascript"></script> 里面有个属性可以先让HTML加载完成后,再下载JS吗?
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("你好");
})
所以一般网页开发中js引用放在页面的最底部,而css文件的引入放在head中.
参考:
http://www.cnblogs.com/baochuan/archive/2012/05/29/2524694.html