【问题标题】:I have two questions about relating events to functions我有两个关于将事件与函数联系起来的问题
【发布时间】:2020-07-29 10:36:11
【问题描述】:

下面的表达式是什么意思?

variable.DOMevent = 函数

为什么它不启动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>

【问题讨论】:

    标签: javascript events event-handling dom-events


    【解决方案1】:

    您正在覆盖元素的onmouseovercontainer1container2 仍然指向同一个锚元素。分配给不同的变量不会有任何区别。

    要解决此问题,您可以创建一个新的 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>

    【讨论】:

    • “您正在覆盖元素的鼠标悬停。”。你这是什么意思?其余的很有帮助。谢谢。
    • @user3291759 container1container2 是相同的元素 a。此元素具有 onmouseover 属性。这就像做a.onmouseover = handler1 然后a.onmouseover = handler2。元素的onmouseover 属性设置为handler2
    【解决方案2】:

    container1container2 指向同一个对象,因此您只是覆盖了事件侦听器的回调。

    例如,如果您针对两个不同的元素,您将能够看到两个回调

    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>

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 2019-06-20
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多