为什么我的textarea值没有从getDocumentById改变?

时间:2016-03-25 04:27:20

标签: javascript arrays

我的程序应该找到一个字符串中的字符频率,它确实很棒。但是,它只能从textarea的初始值开始。我需要它来更新。任何想法?这是家庭作业,所以如果你可以保持你的答案更多" guidline风格"比起"复制和粘贴样式",非常感谢。

<!DOCTYPE>
<html>
    <head>
        <meta charset="utf-8">
        <title>THE BEST HOMEWORK EVA!</title>
        <script type="text/javascript">
            window.addEventListener("load", start, false);

            var string;
            var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
            var freq = [];

            function start() {
                var button = document.getElementById("countButton");
                button.addEventListener("click", getFrequency, false);
            }

            function getFrequency() {
                string = document.getElementById("inputElement").innerHTML;
                var totalCharacters = string.length;
                for (var i = 0; i < 26; i++) {
                    freq[i] = 0;
                    for (var j = 0; j < string.length; j++) {
                        if (string.charAt(j) == arr[i]) {
                            ++freq[i];
                        }
                    }
                }
                document.write(document.getElementById("inputElement").innerHTML);
                //initialize table
                document.writeln("<table style = \"text-align: center\" border = \"1\">");
                document.writeln("<th>Letter</th><th>Count</th><th>Frrequency</th>")
                //construct table by row
                for (var i = 0; i < 26; i++) {
                    document.writeln("<tr><td>" + arr[i] + "</td>");
                    document.writeln("<td>" + freq[i] + "</td>");
                    document.writeln("<td>" + (freq[i] / totalCharacters * 100) + "%</td></tr>");
                }
                //end table
                document.writeln("</table>");
            };
        </script>
    </head>
    <body>
        <h1>Computer Letter Frequency</h1>
        <form action ="#">
            <h2>Input:<input id="countButton" type="button" value="Count!" /></h2>
            <p>
                <textarea id="inputElement" rows="12" cols="80" >Enter your text here....</textarea>
            </p>
            <h2>Results:</h2>
            <div id="outputElement"></div>
        </form>
    </body>
</html>

2 个答案:

答案 0 :(得分:3)

innerHTML的{​​{1}}在您输入内容时不会发生变化,因此:

<textarea>
无论inputElement的值有多大变化,

总是将string = document.getElementById("inputElement").innerHTML 设置为同一个东西。

它的string属性发生了变化,因此您可以通过value获得更好的运气。

答案 1 :(得分:0)

  

我需要它来更新。

这部分让我很困惑,所以我做了这些改变。

  1. 只要您输入文字区域,它就会更新计数。(动态更新)
  2. 当文本字段为空时,它不会显示该表。
  3. 您无需预先定义字符。
  4. 它还包括空格和特殊字符。
  5. 无需点击按钮。
  6. 这是代码。对于html部分,您可以点击here

    window.onload = function(){  // Execute the function when window is completly laoded
              var alphaObject = [];
              var txtArea = document.getElementById('inputElement');
              txtArea.addEventListener('keyup',function(event){// update table on key up from text area
                  alphaObject.length = 0; // empty the array which contain characters
                  var getTxtLength = txtArea.value.length; 
                  if(getTxtLength ===0){
                     // dont show table if text area is empty
                     document.getElementById('outputElement').classList.add('hide');
                  }
                  else{
                    //break the input string and put all characters in array
                    alphaObject = txtArea.value.split('');
                    var m = _getWordCnt();
                    document.getElementById('outputElement').classList.remove('hide');
                    document.getElementById('outputElement').classList.add('show');
                  _createTable(m,txtArea.value.length);
                  }
    
              })
    
                /* This function create an object. For example if my string is "aabbc"
                it will return an object {a:2,b:2,c:1}
                which mean there is 2 occurence of a & b and 1 occurence of c
                Used reduce function of js array to acheive this
                */
                function _getWordCnt(){
                         return alphaObject.reduce(function(prev,next){
                         prev[next] = (prev[next] + 1) || 1;
                        return prev;
                        },{});
                      }
    
                /*Creating table tbody and updating the values
    
                */
    
                function _createTable(obj,stringLength){
                    var tbody = document.createElement('TBODY');
                    var crtRow="";
                     for(var key in obj){ // looping through the object
                           var charOccurence = ((obj[key])/stringLength)*100;
                          crtRow += '<tr><td>'+key+'</td><td>'+obj[key]+'</td><td>'+charOccurence+' %</td></tr>'
                      }
                     document.getElementById("tabBody").innerHTML="";
                     document.getElementById('tabBody').innerHTML=(crtRow);
                }
    }
    

    DEMO & FULL CODE