jQuery 在函数中使用 '$(this)'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9122254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using '$(this)' In A Function
提问by Combobreaker
I am creating a menu that opens and closes using jQuery. In simple terms, it works like this:
我正在创建一个使用 jQuery 打开和关闭的菜单。简单来说,它的工作原理是这样的:
function open_menu() {
$(this).next('ul.sub-menu').css('display', 'block').stop(true, false).animate({
width: '235px',
}, 500);
}
function close_menu() {
// close code here
}
status = 'closed'; // set the default menu status
$('a').click(function() {
switch(status) {
case 'closed':
open_menu();
break;
case 'open':
close_menu();
break;
}
}
If I take the contents of open_menu()
and put it in place of open_menu()
in the .click()
event, every works as expected. If I use the code as show above, $(this)
can not figure out that .click()
fired it and the code does not run.
如果我拿的内容open_menu()
并把它代替open_menu()
的.click()
情况下,预期每个作品。如果我使用上面显示的代码,$(this)
则无法确定是否.click()
触发了它并且代码不会运行。
Is there something that I can do to have the $(this)
selector negotiate what fired it while keeping it in open_menu()
?
我可以做些什么来让$(this)
选择器在保留它的同时协商触发它的原因open_menu()
吗?
回答by Alec Gorge
The this
that you refer to in open_menu
is the context of the open_menu
function, not the click handler of the link. You need to do something like this:
在this
你指的open_menu
是在上下文open_menu
功能,而不是链接的点击处理程序。你需要做这样的事情:
open_menu(this);
function open_menu(that) {
$(that).next(...
回答by James Montagne
You can use apply to set the value of this
in the function.
您可以使用 apply 来设置this
函数中的值。
open_menu.apply(this)
回答by Daniel A. White
Why not just pass it in as a parameter?
为什么不把它作为参数传入?
function open_menu($this) {
$this.next('ul.sub-menu').css('display', 'block').stop(true, false).animate({
width: '235px',
}, 500);
}
function close_menu() {
// close code here
}
status = 'closed'; // set the default menu status
$('a').click(function() {
switch(status) {
case 'closed':
open_menu($(this));
break;
case 'open':
close_menu();
break;
}
}