다음은 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);
});
});
그냥'$ (function() {/// your call});로 감싸십시오; – vittore