【问题标题】:Jquery - Difference between event.target and this keyword?Jquery - event.target 和 this 关键字之间的区别?
【发布时间】:2010-04-16 15:22:24
【问题描述】:

event.targetthis 有什么区别?

假设我有

$("test").click(function(e) {
    $thisEventOb = e.target;
    $this = this;
    alert($thisEventObj);
    alert($this);
});

我知道警报会弹出不同的值。任何人都可以解释其中的区别吗?谢谢一百万。

【问题讨论】:

    标签: javascript jquery html dom


    【解决方案1】:

    如果您单击事件被操纵的元素,它们将是相同的。然而,如果你点击一个 child 并且它冒泡,那么this 指的是这个处理程序绑定到的元素,e.target 仍然指的是事件起源的元素。

    您可以在这里看到不同之处:http://jsfiddle.net/qPwu3/1/

    鉴于此标记:

    <style type="text/css">div { width: 200px; height: 100px; background: #AAAAAA; }​</style>    
    <div>
        <input type="text" />
    </div>​
    

    如果你有这个:

    $("div").click(function(e){
      alert(e.target);
      alert(this);
    });
    

    点击&lt;input&gt; 会提醒输入,然后是 div,因为输入引发了事件,当它冒泡时 div 会处理它。但是,如果你有这个:

    $("input").click(function(e){
      alert(e.target);
      alert(this);
    });
    

    它总是会提醒输入两次,因为它既是事件的原始元素,也是处理它的元素。

    【讨论】:

      【解决方案2】:

      事件可以附加到任何元素。但是,它们也适用于所述对象中的任何元素。

      this 是事件绑定的元素。 e.target 是实际被点击的元素。

      例如:

      <div>
        <p>
          <strong><span>click me</span></strong>
        </p>
      </div>
      <script>$("div").click(function(e) {
        // If you click the text "click me":
        // e.target will be the span
        // this will be the div
      });  </script>
      

      【讨论】:

        【解决方案3】:

        清脆的答案

        this 为您提供实际附加事件的 DOM 元素的引用。

        event.target 为您提供事件发生的 DOM 元素的引用。

        长答案

        jQuery(document).ready(function(){
            jQuery(".outer").click(function(){
        	   var obj = jQuery(event.target);
        	   alert(obj.attr("class"));
            })
        })
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div class="outer">
                Outer div starts here
        	<div class="inner">
        	    Inner div starts here
        	</div>
        </div>

        当你运行上面的代码sn-p你会看到event.target正在提醒真正被点击的div的类名。

        然而,this 会给出绑定点击事件的 DOM 对象的引用。检查下面的代码 sn-p 以了解 this 是如何工作的,即使您单击内部 div,也会始终提醒绑定 click 事件的 div 的类名。

        jQuery(document).ready(function(){
          jQuery(".outer").click(function(){
            var obj = jQuery(this);
            alert(obj.attr("class"));
          })
        })
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div class="outer">
            Outer div starts here
            <div class="inner">
        	    Inner div starts here
            </div>
        </div>

        【讨论】:

          猜你喜欢
          • 2012-08-18
          • 1970-01-01
          • 2016-08-24
          • 2013-10-23
          • 2019-01-17
          • 1970-01-01
          • 2011-04-30
          • 1970-01-01
          • 2017-12-22
          相关资源
          最近更新 更多