내 앱에 JS 카운터를 구현했습니다. 내 두 개의 다른 카운터가 작동해야하는 두 개의 양식 필드가 있습니다. A #post_title
및 #body-field
.내 카운터가 예상대로 작동하지 않는 이유
이 내 JS입니다 :
counter = function() {
\t var title_value = $('#post_title').val(); \t \t
var body_value = $('#body-field').val();
if (title_value.length == 0) {
$('#wordCountTitle').html(0);
return;
}
if (body_value.length == 0) {
$('#wordCountBody').html(0);
return;
}
var regex = /\s+/gi;
var wordCountTitle = title_value.trim().replace(regex, ' ').split(' ').length;
var wordCountBody = body_value.trim().replace(regex, ' ').split(' ').length;
$('#wordCountTitle').html(wordCountTitle);
$('#wordCountBody').html(wordCountBody);
};
$(document).on('ready page:load', function() {
$('#count').click(counter);
\t $('#post_title, #body-field').on('change keydown keypress keyup blur focus', counter);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="title">Title</label>
<textarea id="post_title" placeholder="Enter Title"></textarea>
<span id="wordCountTitle">0</span> words<br/>
<label for="report">Report</label>
<textarea id="body-field"placeholder="Provide all the facts." rows="4">
</textarea><br />
<span id="wordCountBody">0</span>/150 words
</body>
</html>
$(document).ready(ready);
이전에 내가 간결성을 위해 남겨 파일의라는 var ready = function()
에 해당 겉으로는 부유. 하지만 문제가 될 수 있다고 생각되는 순서대로 document.ready()
전화를 남겼습니다.
그래서 내가 가지고있는 문제는 #post_title
필드를 클릭하고 카운터를 업데이트하지 않는 단어를 입력 할 때마다 발생합니다. 그러나 #body-field
을 클릭하고 입력을 시작하면 #body-field
의 카운터가 즉시 업데이트되기 시작하지만 #post_title
의 카운터도 작동하기 시작하고 해당 필드에 올바른 단어 수가 표시됩니다.
이 문제의 원인은 무엇일까요? 1
편집 그냥 내가 오류가 너무 다른 상태로 존재한다는 것을 깨달았다 코드와 함께 연주. 제목을 입력하기 전에 두 번째 입력란 (예 : #body-field
)에 텍스트를 추가하면 본문 입력란의 카운터가 증가하지 않습니다. #post_title
에 제목을 입력하기 시작한 후에 만 업데이트됩니다. 그래서 그들은 어떻게 든 연결되어 있습니다.
이 이름은 잘못된 이름이지만,'# post-title'이 아닐 수도 있습니다. 맞습니까? (하나는 하이픈, 다른 하나는 밑줄을 사용) –
HTML을 공유 할 수 있습니까? 바이올린 데모가 더 좋습니다. – Farhan
@DanHeberden 그게 그렇게 쉬웠 으면 좋겠다. 아니요, 이름이 맞습니다. 내가 말하는 정확한 동작을 볼 수 있도록 코드 스 니펫을 추가했습니다. 제목에 코드를 추가하고 본문 탭을 클릭하면 의미를 알 수 있습니다. – marcamillion