用addListener方法 每次点击都会添加一次方法 这样不好
我希望添加一次,在点击add按纽就不在给div添加方法了
恩 我的问题是 判断div时候已经有了onclick事件 不是去判断时候已经点了add按纽
<!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=gb2312" />
<title>无标题文档</title>
</head><body>
<div id='test' style="height:100px; width:100px; background-color:#0000FF"></div>
<input value="add"type="button" onclick="add()"/>
<script type="text/javascript">
function addListener(element,e,fn){
element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" + e,fn)
};
function add(){
//这里该怎么写 判断已经有了这个方法了
addListener(document.getElementById('test'),'click',function(){alert('a')});
}
</script>
</body>
</html>
我希望添加一次,在点击add按纽就不在给div添加方法了
恩 我的问题是 判断div时候已经有了onclick事件 不是去判断时候已经点了add按纽
<!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=gb2312" />
<title>无标题文档</title>
</head><body>
<div id='test' style="height:100px; width:100px; background-color:#0000FF"></div>
<input value="add"type="button" onclick="add()"/>
<script type="text/javascript">
function addListener(element,e,fn){
element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" + e,fn)
};
function add(){
//这里该怎么写 判断已经有了这个方法了
addListener(document.getElementById('test'),'click',function(){alert('a')});
}
</script>
</body>
</html>
第一种:在add函数的末尾添加一句代码,移除add元素的onclick事件(前提是这个add函数的功能只是为test元素添加事件监听器):function add(event) {
// code
event = event || window.event;
var target = event.target || event.srcElement;
target.onclick = null;
}第二种:用一个标记来控制function add(event) {
if(!arguments.callee.$hasClicked) {
addListener(document.getElementById('test'),'click',function(){alert('a')});
}
}
add.$hasClicked = false;第三种:在页面加载完毕后直接添加监听器(不再每次点击add的时候添加)<!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" />
<title>无标题文档</title>
</head><body>
<div id='test' style="height:100px; width:100px; background-color:#0000FF"></div>
<input value="add"type="button" onclick="add()"/>
<script type="text/javascript">
function addListener(element,e,fn){
element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" + e,fn)
};
function add(){
var tst = document.getElementById('test');
tst.click();
}
window.onload = function() {
addListener(document.getElementById('test'),'click',function(){alert('a')});
};
</script>
</body>
</html>