Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

addEventListener 为什么事件默认就执行了?

以下代码,给class="inner"元素添加点击事件,但是打开浏览器事件就被执行了,并且传入的事件对象是undefined

<body>
<div class="outer">
    o
    <div class="inner">i</div>
</div>
<script type="text/javascript" src='./util/util.js'></script>
<script type="text/javascript">
    var dOuter=document.querySelector('.outer');
    var dInner=document.querySelector('.inner');
    dInner.addEventListener('click',conInfo(event),false);
    dOuter.addEventListener('click',conInfo(event),false);
    function conInfo(event){
        console.log('event...');
        console.log(event);
    }
</script>
</body>

打开浏览器 事件就执行了,并且传入的event=undefined
clipboard.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

clipboard.png

去掉里面的参数,不能这么写。

conInfo 是一个函数, 你在它后面加上 (event), 相当于执行了

函数,而event是未定义的参数,所以会显示函数已执行,并打印出

undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...