为什么单词计数与读取字数不匹配?

时间:2015-06-03 18:27:22

标签: javascript

我使用以下代码进行速读模拟。 它的工作正常。但是我已经在框中粘贴了500个单词,在读完所有单词后,单词数与输入单词数不同。



$('#sim').each(function(){
        this.contentEditable = true;
    });
    
    var go = $('#go');
    var stop = $('#stop');
    var wordCount = 0;
    var wordCountBox = $('#wordCountBox');
    var timepassed = $('#timepassed');
    var textRead = $('#textRead');
    
    
    go.on("click", function(e){
        e.preventDefault();
        startSim();
    });
    
    function startSim(){
        var speed = $('#speed').val();
        timeStart = $.now();
        var sim = $('#sim').text();
        var wordArray = sim.split(" ");
        var simWrap = $('#sim');
        
        var arrCount = wordArray.length;
        var alreadyRead = [];
        
        for (var i = 0; i < arrCount; i++) {
            (function(index) {
                setTimeout(function() { 
                    var pos = index;
                    if(pos < 0){
                        pos = 0;
                    }
                    alreadyRead.push(wordArray[pos]);
                    wordArray[pos] = '<b>'+wordArray[pos]+'</b>';
                    var words = wordArray.join(" ");
                    simWrap.html(words);                
                    wordCount++;
                    if(pos == (arrCount - 1)){
                        triggerDone();
                    }
                }, i * speed);
             })(i);
        }
        // Function done
        function triggerDone(){
            wordCountBox.text(wordCount+' Words Read');
            var timeEnd = $.now();
            var timeRes = timeEnd - timeStart;
            timeRes = parseInt(timeRes);
            timeRes = timeRes / 1000;
            timepassed.text(timeRes+" seconds have passed");
            alreadyRead = alreadyRead.join("");
            textRead.text(alreadyRead);
            var summary = $('#summary');
            summary.show();
            return;
        } 
        stop.on("click", function(e){
            e.preventDefault();
            triggerDone();
        });
    }
&#13;
#sim{
        width:800px;
        height:300px;
        border:solid 1px #2e2e2e;
        color:#2e2e2e;
        padding:5px;
    overflow:auto;
    border:9px outset #0ADA0A;
    margin-top:1em;
    }
&#13;
<div id="sim"></div>
&#13;
&#13;
&#13;

为什么计算单词计数?

还有一个疑问,就是在阅读单词时如何自动滚动。

有人可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

第一个问题是:

<?php $myCookie = $_COOKIE['name_of_cookie'];

在这种情况下,每次遇到空格时,它都会为数组创建一个新的“单词”...所以字符串如下:

var wordArray = sim.split(" ");

将返回长度为6的数组。使用正则表达式...

var words = "foo bar bim baz";

..它将解决这个问题。