240
世界上有10种人,一种懂二进制,另一种不懂二进制。

div的onclick事件怎么失效了?

1 前言

div是用拼接复制到另一个个div上,div的onclick事件中方法名为close,导致onclick=“close()” 触发不了,然后换了名称就可以了

2 代码

<!DOCTYPE html>
<html>
<head>
	<title>test</title>
</head>
<body>

<div id="open"></div>
<div id="close"></div>
<div id="close1"></div>
<div id="close2" onclick="close2()">
	关闭展示区2(div非拼接,(onclick=close2()))
</div>

<div id="area" style="background-color: red">展示区在此</div>

</body>
</html>
<script type="text/javascript">
	var html = `<div  cursor: pointer; onclick='close()'>点击关闭展示区(onclick=close())</div>`

document.querySelector('#close').innerHTML = html;

var html = `<div onclick='close2()'>点击关闭展示区(onclick=close2())</div>`

document.querySelector('#close1').innerHTML = html;

var html = `<div onclick='show()'>点击打开展示区</div>`

document.querySelector('#open').innerHTML = html;
//此方法无法被触发,
function close(){
     document.querySelector('#area').style.display='none';
 }

 function close2(){
     document.querySelector('#area').style.display='none';
 }

 function show(){
     document.querySelector('#area').style.display='block';
 }

</script> 

分析:因为close是window的方法,所以不管拼接出来的还是原先写好的onclick方法都是一样的。

//在console输入
close
ƒ () { [native code] }

 

3 参考

3.1 用JS添加的DIV,无法触发onclick事件 请求帮助 

 

posted @ 2019-02-22 11:03  unionline  阅读(9446)  评论(0编辑  收藏  举报