遇到麻烦指事件对象在一个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文档:“事件对象保证传递给事件处理程序。”我的问题是:如果我没有明确地通过它,它在哪里? ;)?
没有工作 - 仍然返回undefined。 :(由于jQuery正在调用函数,并且(可能)传递参数,比如哪个对象触发了该函数,为什么jQuery对象不会有意义? – Summer 2010-03-10 21:18:11
@Summer - 因为src'不是jQuery对象的属性。如果你真的想在这个上下文中包装'this'(这是引发该事件的元素),那么你可以使用'$(this).attr('src')'来获得' src'属性,这是很多不必要的包装和函数调用,尽管如此, – 2010-03-10 21:44:57
Aha。谢谢你的解释。 – Summer 2010-03-10 21:57:28