我有两个关于将事件与函数相关联的问题
I have two questions about relating events to functions
下面的表达式是什么意思?
variable.DOMevent = function
为什么它不启动 handler1
而只启动 handler2
?
var a = document.querySelector("a");
var container1 = a;
container1.onmouseover = container1.onmouseout = handler1;
var container2 = a;
container2.onmouseover = container2.onmouseout = handler2;
function handler1 (event) {
console.log('handler1: '+event.type);
}
function handler2 (event) {
console.log('handler2: '+event.type);
}
a {
cursor: pointer;
}
<div>
<a>hover me</a>
</div>
您正在覆盖元素的 onmouseover
。 container1
和 container2
仍然指向同一个锚元素。分配给不同的变量不会有任何区别。
要解决此问题,您可以创建一个新的 superHandler
函数,它将调用其中的其他处理函数。
function handler1(event) {
console.log('handler1: ' + event.type);
}
function handler2(event) {
console.log('handler2: ' + event.type);
}
function superHandler(e) {
handler1(e)
handler2(e)
}
const a = document.querySelector("a");
a.onmouseover = a.onmouseout = superHandler;
a {
cursor: pointer;
}
<div>
<a>hover me</a>
</div>
container1
和 container2
指的是同一个对象,所以你只是覆盖事件侦听器的回调。
例如,如果您针对两个不同的元素,您将能够看到这两个回调
var a = document.querySelector("a");
var b = document.querySelector("span");
var container1 = a;
container1.onmouseover = container1.onmouseout = handler1;
var container2 = b;
container2.onmouseover = container2.onmouseout = handler2;
function handler1 (event) {
console.log('handler1: '+event.type);
}
function handler2 (event) {
console.log('handler2: '+event.type);
}
a {
cursor: pointer;
}
<div>
<a>hover me 1</a>
<span>hover me 2</span>
</div>
下面的表达式是什么意思?
variable.DOMevent = function
为什么它不启动 handler1
而只启动 handler2
?
var a = document.querySelector("a");
var container1 = a;
container1.onmouseover = container1.onmouseout = handler1;
var container2 = a;
container2.onmouseover = container2.onmouseout = handler2;
function handler1 (event) {
console.log('handler1: '+event.type);
}
function handler2 (event) {
console.log('handler2: '+event.type);
}
a {
cursor: pointer;
}
<div>
<a>hover me</a>
</div>
您正在覆盖元素的 onmouseover
。 container1
和 container2
仍然指向同一个锚元素。分配给不同的变量不会有任何区别。
要解决此问题,您可以创建一个新的 superHandler
函数,它将调用其中的其他处理函数。
function handler1(event) {
console.log('handler1: ' + event.type);
}
function handler2(event) {
console.log('handler2: ' + event.type);
}
function superHandler(e) {
handler1(e)
handler2(e)
}
const a = document.querySelector("a");
a.onmouseover = a.onmouseout = superHandler;
a {
cursor: pointer;
}
<div>
<a>hover me</a>
</div>
container1
和 container2
指的是同一个对象,所以你只是覆盖事件侦听器的回调。
例如,如果您针对两个不同的元素,您将能够看到这两个回调
var a = document.querySelector("a");
var b = document.querySelector("span");
var container1 = a;
container1.onmouseover = container1.onmouseout = handler1;
var container2 = b;
container2.onmouseover = container2.onmouseout = handler2;
function handler1 (event) {
console.log('handler1: '+event.type);
}
function handler2 (event) {
console.log('handler2: '+event.type);
}
a {
cursor: pointer;
}
<div>
<a>hover me 1</a>
<span>hover me 2</span>
</div>