我有一个简单的文本区域,我正在尝试进行字数统计:
<textarea rows="20" id="inputText" data-bind="textInput: inputText"></textarea>
<p>Total words: <span id="totalWords" data-bind="text: wordCount"></span></p>
当我使用jquery时,单词计数效果非常好:
//get the count of words
var val = $.trim($('textarea').val()),
words = val.replace(/\s+/gi, ' ').split(' ');
$('#totalWords').html(words.length);
但是当我尝试在knockoutjs中执行此操作时,它从1开始并在输入下一个单词的第一个字母时递增:
function appViewModel() {
this.inputText = ko.observable("");
this.wordCount = function () {
var val = $.trim(this.inputText());
var words = val.replace(/\s+/gi, ' ').split(' ');
return words.length;
};
...
}
ko.applyBindings(new appViewModel());
最终我希望能够使用以下内容获取单词数组:
this.words = function () {
var val = $.trim(this.inputText());
var words = val.replace(/\s+/gi, ' ').split(' ');
return words;
};
然后使用单独的函数进行计数:
this.wordCount = ko.computed(function(){
return this.words.length;
});
因为我想对单词数组执行其他操作 - 例如列表和重复单词数的计数。
答案 0 :(得分:2)
试试这个:
function appViewModel() {
this.inputText = ko.observable('');
this.words = function() {
return this.inputText().trim().split(' ').filter(function(w) { return !!w; });
};
};
ko.applyBindings(new appViewModel());
HTML:
<textarea rows="20" id="textInput" data-bind="textInput: inputText"></textarea>
<p>Total words: <span id="totalWords" data-bind="text: words().length"></span></p>
请参阅Fiddle
答案 1 :(得分:0)
这样的事情:
function appViewModel() {
var self = this;
this.inputText = ko.observable("");
this.wordCount = ko.computed(function () {
var val = self.inputText();
var words = val.split(/\s+/).filter(function (item) {
return item.length > 0;
});
return words.length;
});
}
ko.applyBindings(new appViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<textarea rows="10" id="inputText" data-bind="textInput: inputText"></textarea>
<p>Total words: <span id="totalWords" data-bind="text: wordCount"></span>
</p>
<p data-bind="text: inputText"></p>