错误消息:this.stopPropagation不是函数

Error Message: this.stopPropagation is not a function

本文关键字:函数 stopPropagation this 消息 错误      更新时间:2024-02-08

有人能向我解释为什么我在使用stopPropagation方法时会收到此错误消息吗?我有一个简单的事件,如果您单击id为ex1div,将运行一个函数,该函数将导致div的背景色为深粉红色。然后我添加了stopPropagation方法来停止该函数。但是,我在控制台中收到一条错误消息,说它不起作用,然而,stopPropagation方法仍然有效。

HTML

<div id="ex1"><h2>Example 1</h2><p></p><h4>results:</h4></div>

Javascript

document.getElementById('ex1').addEventListener('click', function(e){
this.stopPropagation();
this.style.backgroundColor = 'deeppink';
},false);

不要使用thisthis指的是单击的元素。使用e,它是事件对象。

Mozilla文档

document.getElementById('ex1').addEventListener('click', function(e){
e.stopPropagation();
this.style.backgroundColor = 'deeppink';
},false);
<div id="ex1"><h2>Example 1</h2><p></p><h4>results:</h4></div>