http://jsfiddle.net/khE4A/4/
var expandTextarea = function() {
//Note that this is in a scope such that the click, blur and change handlers can all see it
var typed = false;
$('.js-textarea-slide').on('click', function(e) {
//If you bind the change handler in here, it will be bound every time the click event
//is fired, not just once like you want it to be
$(this).animate({
height: '100'
}, 0);
}).change(function() {
typed = true;
});
//Note that I got rid of typed and e.
//If typed were included here, it would not have the value of the typed on line 4.
//Rather, it would have the value of whatever jQuery's event processing passes as the first
//parameter. In addition, it would hide the typed on line 4 from being accessible since
//they have the same name.
//Also, I got rid of the e parameter because it's not used, and in JavaScript, it's perfectly
//acceptable to have a paramter calling/definition count mismatch.
$('.js-textarea-slide').blur(function() {
if (!typed) {
$(this).animate({
height: '50'
}, 0);
}
});
};
//Since expandTextarea doesn't depend on the context it's called from, there's no need to wrap it
//in an extra function.
$(expandTextarea);
请注意,这遵循您在问题中描述的逻辑,而不是您的代码尝试执行的操作。无论如何,一些重要的变化:
每次单击文本区域时都会绑定您的更改事件,而不是一次。例如,如果您单击 textarea 3 次,您将绑定事件 3 次,而不是只需要 1 次。
此外,实际上导致代码损坏的部分是 typed 超出了模糊处理程序的范围。给回调一个具有特定名称的参数不会将该变量拉入范围。事实上,如果变量在以前可访问的范围内,它会屏蔽它。
另一个[迂腐]的事情:
$(function() {
expandTextarea();
});
函数包装是不必要的。由于expandTextarea不使用this
,可以直接使用该函数:
$(expandTextarea);
无论如何,鉴于您问题中的问题描述,我相信您正在寻找的是:http: //jsfiddle.net/khE4A/2/