代码之家  ›  专栏  ›  技术社区  ›  Summer

如何从外部函数引用事件对象?- jQuery

  •  1
  • Summer  · 技术社区  · 15 年前

    我在引用jquery函数中的事件对象时遇到问题:

    // Execute a function when an image with the arrow class is clicked
    $('.arrow').bind('click',update_support);
    
    // Function tries to refer to the calling image using $(this)
    function update_support() {
      alert( $(this).src );
    }
    
    // Result: an alert of 'undefined'
    

    这段代码确实有效,但是它显式地将“this”对象传递给函数,我觉得一定有更好的方法:

    $('.arrow').bind('click',update_support(this));
    
    function update_support(obj) {
      alert( obj.src );
    }
    
    // Result: an alert with the src of the clicked image
    

    编辑以使我的问题更清楚: 为什么必须显式地为函数提供任何参数?来自jquery文档 http://api.jquery.com/category/events/event-object :“事件对象保证传递给事件处理程序。”我的问题是:如果我不显式传递它,它在哪里??)

    3 回复  |  直到 15 年前
        1
  •  2
  •   brettkelly    15 年前
    $('.arrow').bind('click',function(event){ update_support(event);} );
    

    未测试,但应将对事件的引用传递到 update_support .

    编辑 :您还需要修改 更新支持 ,显然:

    function update_support(evt) {
      alert( evt.target.src );
    }
    
        2
  •  1
  •   James    15 年前

    而不是:

    alert( $(this).src );
    

    尝试:

    alert( this.src );
    

    $(this) 是一个jquery对象。 this 是一个dom元素。

        3
  •  1
  •   Community CDub    8 年前

    作为两者的替代 inkedmn S和 J-P 的答案

    // Execute a function when an image with the arrow class is clicked
    $('.arrow').bind('click',update_support);
    
    // Function tries to refer to the calling image using $(this)
    function update_support(e) {
      alert( e.target.src );
    }
    

    e 在这种情况下 event 对象(跨浏览器标准化)

    如果未在事件处理程序签名中显式定义事件对象参数的参数,则可以使用 arguments

    // Execute a function when an image with the arrow class is clicked
    $('.arrow').bind('click',update_support);
    
    // Function tries to refer to the calling image using $(this)
    function update_support() {
      alert( arguments[0].target.src );
    }
    

    但在我看来,通过显式地为事件对象参数定义一个参数,可以使代码更容易阅读。