jQuery:如何将$(this)作为函数参数传递? [英] jQuery: How do you pass $(this) as function parameter?

查看:1007
本文介绍了jQuery:如何将$(this)作为函数参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到的所有jQuery示例都具有内联函数.

All jQuery examples I see has in-line functions.

如果该函数相当长,或者该函数是可重用的,我可能要分离该函数.

If the function is pretty long, or if the function is reusable, I may want to separate the function.

例如,我该如何转动

$('#myElement').click(function(){
  $(this).addCss('clicked');
})

变成这样

$('#myElement').click(ElementClicked($(this))

function ElementClicked(???){
  ???.addCss('clicked');
}

谢谢!

推荐答案

这不起作用:

$('#myElement').click(ElementClicked($(this)));

这将使用编写时的this值执行函数ElementClicked(),并将ElementClicked()返回值绑定到click事件.在这种情况下,什么都没有.

This is executing the function ElementClicked() with whatever this is at the time of writing, and binds the return value of ElementClicked() to the click event. Which in this case is nothing.

您需要函数传递给click事件,如下所示:

You'll need to pass a function to a click event, like so:

$('#myElement').click(function () { ElementClicked($(this)); });

这将创建一个(n个匿名)函数,该函数将绑定到click事件,并且该函数在运行时调用ElementClicked(),并传递this.函数ElementClicked可以定义为:

This makes a(n anonymous) function, which will be bound to the click event, and the function calls ElementClicked() when run, passing this. The function ElementClicked can be defined as:

function ElementClicked(elem) {
  elem.addClass('clicked');
}

尽管您会注意到,绑定到事件的函数内的this将是clicked元素.因此,与其制作一个调用元素传递函数的函数包装器,不如将其缩写为:

As you will notice though, this inside the function that is bound to the event will be the clicked element. So instead of making a function wrapper that calls a function passing the element, you can just abbreviate it like so:

$('#myElement').click(ElementClicked);

function ElementClicked() {
  $(this).addClass('clicked');
}

请注意,该函数像变量一样传递给click(),而不是立即执行,因为它后面没有方括号().

Notice that the function is passed to click() like a variable instead of being executed immediately, because there are no brackets () following it.

顺便说一句,您可能是说addClass而不是addCss.

And BTW, you probably mean addClass instead of addCss.

这篇关于jQuery:如何将$(this)作为函数参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆