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事件 請求幫助
