[英].css function does not work inside of handler function
I want to change css properties inside of a named function thant handles the click event. 我想更改命名函数内部的CSS属性,然后处理click事件。 If I call .css in an anonymous function defined in the click event, it works.
如果我在click事件中定义的匿名函数中调用.css,它将起作用。 However, I want to call .css inside of a named function defined inside the handler function.
但是,我想在处理函数内定义的命名函数内调用.css。 Here's my code.
这是我的代码。
$(document).ready(function () {
$('#popup').click(partial(coolTransition, $(this)));
});
function coolTransition(elem) {
shrink();
function shrink() {
elem.css('background-color', '#000000');
}
}
//used to implement partial function application so that I can pass a handler reference that takes arguments.
//see http://stackoverflow.com/questions/321113/how-can-i-pre-set-arguments-in-javascript-function-call-partial-function-applic
function partial(func /*, 0..n args */ ) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
}
Thanks in advance for help. 在此先感谢您的帮助。
What do you think $(this)
refers to in the second line? 您认为
$(this)
在第二行中指的是什么? It is not $('#popup')
. 不是
$('#popup')
。 If you want to refer to it, you have to create a reference first: 如果要引用它,则必须先创建一个引用:
$(document).ready(function () {
var $popup = $('#popup');
$popup.click(partial(coolTransition, $popup));
});
That said, using partial
is not necessary. 就是说,不必使用
partial
。 You could also do: 您也可以这样做:
$('#popup').click(function() {
coolTransition($(this));
});
or even 甚至
$('#popup').click(function() {
$(this).css('background-color', '#000000');
});
And there are many other ways... 还有许多其他方式...
Btw. 顺便说一句。 defining
shrink
inside coolTransition
seems to be unnecessary. 在
coolTransition
内部定义shrink
似乎是不必要的。 Don't do it unless you have a reason. 除非有理由,否则不要这样做。
In: 在:
$(document).ready(function() {
$('#popup').click(partial(coolTransition, $(this)));
});
$(this)
is $(document)
. $(this)
是$(document)
。 You need $(this)
to take on the context of $('#popup')
, and for this you need a function: 您需要
$(this)
来接受$('#popup')
的上下文,为此,您需要一个函数:
$(document).ready(function() {
$('#popup').click((function() {
return partial(coolTransition, $(this));
})());
});
Alternatively, you can just avoid $(this)
entirely: 或者,您可以完全避免
$(this)
:
$(document).ready(function () {
var $elm = $('#popup');
$elm.click(partial(coolTransition, $elm));
});
Really, though, this whole usage of partial
seems overly complex. 实际上,
partial
整个用法似乎过于复杂。 Why do you think that you need it? 为什么您认为自己需要它? The easiest approach is:
最简单的方法是:
$(document).ready(function() {
$('#popup').click(function() {
coolTransition($(this));
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.