2010-04-07 7 views
0

다음은 jQuery 워드 카운터 용 코드의 일부입니다. 내 질문은 : 페이지를로드 할 때 단어를 카운트하고 결과를 표시하는 부분을 실행하는 방법과 키 업, 클릭, 흐림 등의 이벤트를 수행하는 방법은 무엇입니까? 복사하여 붙여 넣을 수도 있지만 너무 엉성한 것 같습니다. 또는 반복 된 비트를 다른 함수로 가져올 수 있지만 내 $ (this) 변수는 더 이상 작동하지 않습니다. 무엇을해야합니까? ,jQuery : 코드 스 니펫 onload와 바운드 함수를 실행하십시오.

$(this).bind('keyup click blur focus change paste', function() { 
    var numWords = jQuery.trim($(this).val()).replace(/\s+/g," ").split(' ').length; 
    $(this).next('.word-count').children('strong').text(numWords); 
}).keyup(); 

이것은 keyup 이벤트를 한 번 트리거 방금 바인딩 하나를, 그래서이 코드를 실행하면 '

이 부분에
$(".count").each(function() { 

    // Set up max words 
    maxWords = 200; 

    // Set up div to display word count after my textarea 
    $(this).after('<div class="word-count"><strong>0</strong> Words ('+maxWords+' Maximum)</div>'); 

    // Bind function to count the words 
    $(this).bind('keyup click blur focus change paste', function() { 

    // Count the words 
    var numWords = jQuery.trim($(this).val()).replace(/\s+/g," ").split(' ').length; 

    // Display the result 
    $(this).next('.word-count').children('strong').text(numWords); 
    }); 
}); 
+0

그냥'$ (function() {/// your call});로 감싸십시오; – vittore

답변

2

, 단지 다음과 같이 바인딩 후 한 번 트리거 방금 한 번 실행되도록 바인딩 한 처리기를 트리거 할 것입니다.

+0

완벽하게 일했습니다. 고마워요. – Summer