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が1回ではなく、クリックされるたびにバインドされます。たとえば、textareaを3回クリックした場合、必要な1回だけではなく、3回イベントをバインドします。
また、実際にコードが壊れたのは、入力された部分がブラーハンドラーの範囲外であったことです。コールバックに特定の名前のパラメーターを指定しても、その変数はスコープに取り込まれません。実際、変数が以前にアクセス可能なスコープにあった場合は、それをマスクします。
もう1つの[衒学的]なこと:
$(function() {
expandTextarea();
});
関数のラッピングは不要です。ExpandTextareaはを使用しないためthis
、関数を直接使用できます。
$(expandTextarea);
とにかく、あなたの質問の問題の説明を考えると、私はあなたが探しているものは次のとおりだと思います:http: //jsfiddle.net/khE4A/2/