2010-03-10 48 views
1

遇到麻烦指事件对象在一个jQuery功能:如何从外部函数引用事件对象? - 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' 

此代码的工作,但它明确地传递了“这个”对象的功能,我觉得有一定有更好的方式:

$('.arrow').bind('click',update_support(this)); 

function update_support(obj) { 
    alert(obj.src); 
} 

// Result: an alert with the src of the clicked image 

编辑让我更清楚的问题: 为什么我应该给任何参数明确的功能?来自http://api.jquery.com/category/events/event-object的jQuery文档:“事件对象保证传递给事件处理程序。”我的问题是:如果我没有明确地通过它,它在哪里? ;)?

回答

1

相反的:

alert($(this).src); 

尝试:

alert(this.src); 

$(this)是一个jQuery对象。 this是一个DOM元素。

+0

没有工作 - 仍然返回undefined。 :(由于jQuery正在调用函数,并且(可能)传递参数,比如哪个对象触发了该函数,为什么jQuery对象不会有意义? – Summer 2010-03-10 21:18:11

+0

@Summer - 因为src'不是jQuery对象的属性。如果你真的想在这个上下文中包装'this'(这是引发该事件的元素),那么你可以使用'$(this).attr('src')'来获得' src'属性,这是很多不必要的包装和函数调用,尽管如此, – 2010-03-10 21:44:57

+0

Aha。谢谢你的解释。 – Summer 2010-03-10 21:57:28

2
$('.arrow').bind('click',function(event){ update_support(event);}); 

未经测试,但应通过参考事件update_support

编辑:你想也需要修改update_support,明明:

function update_support(evt) { 
    alert(evt.target.src); 
} 
+0

可以工作,但它看起来像OP想''update_support()''中的'event.target'函数,因为他们希望获得用于编辑的'src'属性 – 2010-03-10 21:14:26

+0

+1,尽管包装'update_support'的匿名函数不是必需的 - 事件对象将作为第一个参数传递给它,函数中需要一个参数签名以捕获价值 – 2010-03-10 21:20:07

+0

好吧,你可以像使用'arguments [0]'一样使用'arguments'来引用它,但IMO会让它更容易拥有一个捕获参数值的参数。 – 2010-03-10 21:28:58

1

由于在这种情况下,替代双方inkedmn的和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); 
} 

eevent对象(跨浏览器标准化)

如果你没有在事件处理程序签名的明确定义事件对象参数一个参数,事件对象可以使用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); 
} 

但在我的真实想法被引用,它将使代码更易于阅读通过显式定义事件对象参数的参数。

+0

我试过这个,但是我的浏览器报告,当它没有被明确地传递时,e是未定义的。 – Summer 2010-03-10 21:29:02

+0

当你说它没有明确通过时,你是什么意思?你的意思是从'update_support'函数签名中删除参数吗?在这种情况下,'e'将是未定义的,因为它没有在任何地方定义(不包括变量'e'可以在父范围中声明的概念)。 – 2010-03-10 21:33:32

+0

同意。我的意思是当我不使用.bind('click',update_support(this)),而是尝试使用.bind('click',update_support)或.bind('click',update_support(event)) - 它不会没有工作。也许我会继续处理这个问题,然后留下漂亮的语法。 :) – Summer 2010-03-10 21:38:13

相关问题