[英]Why does my counter not work in the field like I would expect
我在我的應用程序中實現了一個JS計數器。 我有2個表單字段,我的兩個不同的計數器應工作。 #post_title
和#body-field
。
這是我的JS:
counter = function() { var title_value = $('#post_title').val(); 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); $('#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
的計數器#post_title
開始工作並顯示正確數量的單詞那個領域。
是什么原因造成的?
編輯1
只是在玩那個代碼片段時,我才意識到錯誤也存在於另一種狀態。 如果您僅在輸入標題之前先將文本添加到第二個字段(即#body-field
),則body-field的計數器不會增加。 僅在您開始在#post_title
輸入標題后#post_title
。 因此它們都以某種方式鏈接在一起。
您遇到的錯誤是由於這兩個代碼塊
if (title_value.length == 0) {
$('#wordCountTitle').html(0);
return;
}
if (body_value.length == 0) {
$('#wordCountBody').html(0);
return;
}
這意味着為了使計數器運行,標題和正文都應具有一定的價值。 只需刪除兩者的return
,它就可以工作。
編輯
我認為同時刪除兩個if塊也將為您提供所需的行為。 如果要同時擁有兩個if塊,則必須將標題和正文的計數器分開。
編輯2
這是計數器功能的更簡單實現。
counter = function() {
var title_value = $('#post_title').val();
var body_value = $('#body-field').val();
$('#wordCountTitle').html(title_value.split(' ').length);
$('#wordCountBody').html(body_value.split(' ').length);
}
您不應具有counter
功能檢查功能,並且不要在兩個字段上都執行操作。 counter
函數應該執行完全相同的操作,方法是利用jquery內部的this
關鍵字,或者采用event
參數並將其作為替代參數與event.target
。
這是重構:
var counter = function(event) {
var fieldValue = $(this).val();
var wc = fieldValue.trim().replace(regex, ' ').split(' ').length;
var regex = /\s+/gi;
var $wcField = $(this)[0] === $('#post_title')[0] ? $('#wordCountTitle') : $('#wordCountBody');
if (fieldValue.length === 0) {
$wcField.html('');
return;
}
$wcField.html(wc);
};
$(document).on('ready page:load', function () {
$('#post_title, #body-field').on('change keyup paste', counter);
});
另外,我不確定是否在change keyup paste
應該聽這些文本區域上的這么多事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.